溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

vue cli4.0項目如何引入typescript

發(fā)布時間:2020-07-18 09:15:58 來源:億速云 閱讀:242 作者:小豬 欄目:開發(fā)技術

這篇文章主要為大家展示了vue cli4.0項目如何引入typescript,內容簡而易懂,希望大家可以學習一下,學習完之后肯定會有收獲的,下面讓小編帶大家一起來看看吧。

  現(xiàn)有的項目是采用vue cli4.0腳手架生成的,現(xiàn)在想要引入typescript。

  1.執(zhí)行安裝命令

npm install --save-dev typescript
npm install --save-dev @vue/cli-plugin-typescript

  2.根目錄下新建 tsconfig.json

{
 "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 文件,文件內容如下:

declare module '*.vue' {
 import Vue from 'vue';
 export default Vue;
}

  4.修改入口文件后綴

復制代碼 代碼如下:
src/main.js => src/main.ts

  5.改造 .vue 文件

src/main.js => src/main.ts

  加上 lang=ts 可以讓webpack識別此段代碼為 typescript

  6.使用裝飾器插件

  vue-class-component:強化 Vue 組件,使用 TypeScript裝飾器 增強 Vue 組件,使得組件更加扁平化
  vue-property-decorator:在 vue-class-component 上增強更多的結合 Vue 特性的裝飾

  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; // 監(jiān)聽路由變化時的狀態(tài)為前進還是后退
   // 去終節(jié)點左,從終節(jié)點過來右
   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);
   }
 }
   // 彈出系統(tǒng)提示對話框
  showAlert(msg:string) {
   plus.nativeUI.alert(
    msg,
    function() {
     // console.log("User pressed!");
    },
    "報警詳情",
    "確定"
   );
  }
}

以上就是關于vue cli4.0項目如何引入typescript的內容,如果你們有學習到知識或者技能,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI