Vue搭配TypeScript

1. 安装Vue命令行工具

yarn global add @vue/cli

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

vue create hello-vue 勾选TS支持

3. 示例代码

3.1 main.ts

1
2
3
4
5
6
7
8
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<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