在 Vue 中使用 Typescript


前言

  恕我直言,用 Typescript 寫 Vue 真的很難受,Vue 對 ts 的支持一般,如非萬不得已還是別在 Vue 里邊用吧,不過聽說 Vue3 會增強對 ts 的支持,正式登場之前還是期待一下吧嘻嘻。

  本篇不會過多講述 ts 語法,着重記錄下 在 Vue 中使用 ts 的方法以及踩坑經過。

  如果是使用 Vue Cli2 搭建的項目,要注意 webpack 版本可能與 ts-loader 版本不匹配,可以降低 ts-loader 版本到 3.0+ 或者 將 webpack升級到 4.0+ (本篇所用版本 webpack@3.6.0 + ts-loader@3.5.0)

主要步驟

  1. 先要讓 vue 項目可以識別 .ts 文件。安裝關鍵依賴 npm i typescript ts-loader -D

  2. 在 webpack.base.config.js 中添加 ts-loader

//resolve.extensions 里面加上.ts 后綴 之后引入.ts的時候可以不寫后綴
{
  test: /\.tsx?$/,
  loader: 'ts-loader',
  exclude: /node_modules/,
  options: { 
    appendTsSuffixTo: [/\.vue$/], //關鍵
  }
}

  3. 在根目錄建tsconfig.json文件 下面的配置僅供參考

{
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules"
  ],
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "allowJs": true,
    "module": "esnext",
    "target": "es5",
    "moduleResolution": "node",
    "isolatedModules": true,
    "lib": [
      "dom",
      "es5",
      "es2015.promise"
    ],
    "sourceMap": true,
    "pretty": true
  }
}

  4. 接着需要確保在 vue 中可以正常使用 ts 。安裝 vue-class-component(為vue組件提供修飾器) vue-property-decorator(更多的結合vue特性的修飾器) [ tslint tslint-loader tslint-config-standard(可選 約束.ts/.tsx代碼格式)],這樣就可以在 vue 文件中使用諸如 @Component、@Prop等裝飾器了。注意:.vue 文件中的 script 標簽要加上 lang="ts"。關於 裝飾器的使用可以參看下這位大哥的文章:https://segmentfault.com/a/1190000019906321

<template>
    <div class="count-down" v-html="countDown(endDate)">
    </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Emit } from "vue-property-decorator"
import moment from 'moment'

@Component
export default class CountDown extends Vue {
    @Prop() endDate!: string
    // 變量后加!是非空斷言

    now: any = moment()
    mounted() {
        setInterval((): void =>{
            this.now = moment()
        },1000)
    }
    destroyed() {
        
    }
    get countDown(): object{
        return function(endDate: any): string {
            let m1: any = this.now
            let m2: any = moment(endDate)
            let du: any = moment.duration(m2 - m1, 'ms')
            let hours: number = du.get('hours')
            let mins: number = du.get('minutes')
            let ss: number = du.get('seconds')
            if(hours <= 0 && mins <= 0 && ss <= 0) {
                // this.$emit('timeout')
                this.timeout()
                return "今日已結束"
            }else {
                return `${this.PrefixInteger(hours,2)} <span style="font-size: 16px;">小時</span> ${this.PrefixInteger(mins,2)} <span style="font-size: 16px;">分鍾</span><span style="color: #F56C6C;"> ${this.PrefixInteger(ss,2)} </span><span style="font-size: 16px;">秒</span>`
            }
        }
    }

    @Emit()
    timeout(){}

    
    //數字前補 0 
    // num傳入的數字,n需要的字符長度
    PrefixInteger(num: number, n: number): string {
        return (Array(n).join('0') + num).slice(-n)
    }
}
</script>

<style lang="less" scoped>
//...
</style>

 

  5. 將main.js 變成 main.ts 並且在 webpack.base.conf.js 修改入口為main.ts,這一步至關重要。

  6. 在 src 目錄下新建文件 shims-vue.d.ts ,告訴 TypeScript *.vue 后綴的文件可以交給 vue 模塊來處理,注意 在代碼中導入 *.vue 文件的時候,需要寫上 .vue 后綴,這里可以參考官網說明:增強類型以配合插件使用

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

踩坑記錄

  1. 報錯如下,報錯原因一是沒有將入口文件改成 ts,二是 webpack.base.conf.js 中引入 ts-loader 錯誤,沒有加上 options: { appendTsSuffixTo: [/\.vue$/], }

Module build failed: Error: Could not find source file: 'XXX/src/App.vue'.

  2. 全局屬性報錯 如 Vue.prototype.$msg = XXX,需要將全局屬性在 .d.ts 文件中聲明

import Vue from "vue";
import { AxiosInstance } from "axios";
import { ElMessage } from "element-ui/types/message";

declare module "*.vue" {
    export default Vue;
}

declare module 'vue/types/vue' {
    interface Vue {
        $http: AxiosInstance,
        $message: ElMessage
    }
}

  3. 使用上面這種聲明全局屬性的方式又會帶來新的問題,報錯 import App from './App.vue'處,找不到 App.vue 這個模塊,雖然不影響編譯,但是這紅色的波浪線就像老鼠屎,看着那叫一個難受呀。解決方法:將 shims-vue.d.ts 文件一分為二,將全局屬性聲明和 Vue 的聲明分離;在 shims-vue.d.ts 文件同級目錄下新建 vue.d.ts(名字不一定叫 vue,如 xxx.d.ts 也可以);關鍵是要將以下代碼放在單獨的 .d.ts 文件中

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM