現有的項目是採用vue cli4.0腳手架生成的,如今想要引入typescript。vue
1.執行安裝命令node
npm install --save-dev typescript
npm install --save-dev @vue/cli-plugin-typescript
2.根目錄下新建 tsconfig.jsonwebpack
{ "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"] }
3.新增 shims-vue.d.ts
根目錄下新建 shims-vue.d.ts,讓 ts 識別 *.vue 文件,文件內容以下:web
declare module '*.vue' { import Vue from 'vue'; export default Vue; }
4.修改入口文件後綴typescript
src/main.js => src/main.ts
5.改造 .vue 文件npm
<script>替換爲<script lang="ts">json
加上 lang=ts 可讓webpack識別此段代碼爲 typescriptdom
6.使用裝飾器插件ide
vue-class-component:強化 Vue 組件,使用 TypeScript裝飾器 加強 Vue 組件,使得組件更加扁平化
vue-property-decorator:在 vue-class-component 上加強更多的結合 Vue 特性的裝飾this
Demo:
import { Vue, Component ,Watch} from 'vue-property-decorator'; @Component({ components: { Loading } }) export default class App extends Vue{ old_back:object=null, transitionName:string = "slide-right"; get ...mapState("base", ["loadingStatus"]); @Watch('$route') onChangeValue(to:object, from:object){ // console.log('$route', to, from) const noBack = to.meta.noBack; // 監聽路由變化時的狀態爲前進仍是後退 // 去終節點左,從終節點過來右 if (to.meta.last) { this.transitionName = "slide-left"; } else if (from.meta.last) { this.transitionName = "slide-right"; } else if (from.meta.leaf) { // 從其它葉子頁面過來的,往右 this.transitionName = "slide-right"; } else { if (noBack) { // 去到不須要返回的界面往右 this.transitionName = "slide-right"; } else { this.transitionName = "slide-left"; } } } @Watch('loadingStatus') onChangeValue(newVal: string){ if (newVal) { setTimeout(_ => { this.setLoading(false); }, 1500); } } // 彈出系統提示對話框 showAlert(msg:string) { plus.nativeUI.alert( msg, function() { // console.log("User pressed!"); }, "報警詳情", "肯定" ); } }
....