前言
假設已經有一個通過 vue-cli3
腳手架構建的 vue
項目
命令行安裝 Typescript
npm install --save-dev typescript
npm install --save-dev @vue/cli-plugin-typescript
編寫 Typescript
配置
根目錄下新建 tsconfig.json
,下面為一份配置實例(點擊查看所有配置項)。值得注意的是,默認情況下,ts
只負責靜態檢查,即使遇到了錯誤,也僅僅在編譯時報錯,并不會中斷編譯,最終還是會生成一份 js
文件。如果想要在報錯時終止 js
文件的生成,可以在 tsconfig.json
中配置 noEmitOnError
為 true
。
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"allowJs": false,
"noEmit": true,
"types": [
"webpack-env"
],
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"exclude": [
"node_modules"
]
}
新增 shims-vue.d.ts
根目錄下新建 shims-vue.d.ts
,讓 ts
識別 *.vue
文件,文件內容如下
declare module '*.vue' {
import Vue from 'vue'
export default Vue
}
修改入口文件后綴
src/main.js => src/main.ts
改造 .vue
文件
.vue
中使用 ts
實例
// 加上 lang=ts 讓webpack識別此段代碼為 typescript
<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
// ...
})
</script>
一些好用的插件
vue-class-component
:強化 Vue
組件,使用 TypeScript
裝飾器 增強 Vue
組件,使得組件更加扁平化。點擊查看更多
import Vue from 'vue'
import Component from 'vue-class-component'
// 表明此組件接受propMessage參數
@Component({
props: {
propMessage: String
}
})
export default class App extends Vue {
// 等價于 data() { return { msg: 'hello' } }
msg = 'hello';
// 等價于是 computed: { computedMsg() {} }
get computedMsg() {
return 'computed ' + this.msg
}
// 等價于 methods: { great() {} }
great() {
console.log(this.computedMsg())
}
}
vue-property-decorator
:在 vue-class-component
上增強更多的結合 Vue
特性的裝飾。點擊查看更多
import { Vue, Component, Prop, Watch, Emit } from 'vue-property-decorator'
@Component
export default class App extends Vue {
@Prop(Number) readonly propA: Number | undefined
@Prop({ type: String, default: ''}) readonly propB: String
// 等價于 watch: { propA(val, oldval) { ... } }
@Watch('propA')
onPropAChanged(val: String, oldVal: String) {
// ...
}
// 等價于 resetCount() { ... this.$emit('reset') }
@Emit('reset')
resetCount() {
this.count = 0
}
// 等價于 returnValue() { this.$emit('return-value', 10, e) }
@Emit()
returnValue(e) {
return 10
}
// 等價于 promise() { ... promise.then(value => this.$emit('promise', value)) }
@Emit()
promise() {
return new Promise(resolve => {
resolve(20)
})
}
}