白季飞龙的个人主页

Vue搭配TypeScript

1. 安装Vue命令行工具

yarn global add @vue/cli

2. 创建Vue项目,并按提示启用TypeScript

vue create hello-vue 勾选TS支持

3. 示例代码

3.1 main.ts

import Vue from 'vue'
import MyApp from './MyApp.vue';

Vue.config.productionTip = false;

new Vue({
    render: h => h(MyApp),
}).$mount('#app');

3.2 MyApp.vue

<template>
    <div>
        <h3>URL: {{url}}</h3>
        <h4>Loading: {{loading}}</h4>
        <h4>Error: {{error}}</h4>
        <h4>Response:</h4>
        <pre>{{response}}</pre>
    </div>
</template>

<!--suppress JSUnusedGlobalSymbols -->
<script lang="ts">
    import {Component, Vue} from "vue-property-decorator";

    @Component
    export default class MyApp extends Vue {
        url: string = "http://httpbin.org/get";
        loading: boolean = false;
        error: string = "";
        response: string = "<...>";

        mounted(): void {
            console.log("Mounted");
            this.loading = true;
            fetch("http://httpbin.org/get")
                .then(x => x.text())
                .then(x => {
                    this.loading = false;
                    this.response = x;
                })
                .catch(error => {
                    this.loading = false;
                    this.error = error;
                });
        }
    }
</script>

<style scoped>
    pre {
        font-family: Consolas, sans-serif;
    }
</style>

文章首发: https://baijifeilong.github.io


漫漫路,莫论逍遥;潜心修,只为悟道