多是最全的Vue-TypeScript教程(附實例代碼和一鍵構建工具)

圖片描述

Vue-TypeScript-DpApp-Demo

功能

  • 輪播
  • 搜索
  • 列表
  • 懶加載
  • 簡單動畫
  • loading
  • vue-router.ts
  • vuex.ts
  • vue-class-component使用
  • vuex-class使用
  • xxx.d.ts聲明文件
  • 基於類的編寫方式
  • mock數據
  • tsconfig.json
  • webpack配置
  • vue-typescript-cli

項目地址:https://github.com/SimonZhang...javascript

完成後的簡單例子

基於類的寫法加上靜態類型檢查,簡直不能再嗨vue

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { State } from "vuex-class";

@Component
export default class Shops extends Vue {
  @State shops: StoreState.shop[];
  @State searchVal: string;

  get shopList(): StoreState.shop[] {
    const shops = this.shops;
    const searchVal = this.searchVal;
    return shops.filter(
      (el: StoreState.shop) => el.shopName.indexOf(searchVal) > -1
    );
  }
}
</script>

爲何使用TypeScript

1. JavaScript的超集

支持全部原生JavaScript的語法java

2. 強類型語言

如今不少主流語言都是強類型的,而這點也一直是JavaScript所被人詬病的地方。使用TypeScript以後,將會在代碼調試、重構等步驟節省不少時間。node

好比說:函數在返回值的時候可能通過複雜的操做,那咱們若是想要知道這個值的結構就須要去仔細閱讀這段代碼。那若是有了TypeScript以後,直接就能夠看到函數的返回值結構,將會很是的方便

3. 強大的IDE支持

如今的主流編輯器如VSCodeWebStormAtomSublime等都對TypeScript有着很是友好的支持,主要體如今智能提示上,很是的方便webpack

4. 可運行於任何瀏覽器、計算機、操做系統

強大的編譯引擎git

5. 迭代更新快

不斷更新,提供更加方便友好的Apies6

6. 微軟和Google爸爸

TypeScript是微軟開發的語言,而Google的Angular使用的就是TypeScript,因此不用擔憂會中止維護,至少在近幾年內TypeScript都會一門主流開發語言github

7. npm下載量很是高

截止2017.12.17, TypeScript在全球範圍內的npm日均下載量在30w左右,這個數字將近是vue下載量的10倍,可見TypeScript仍是很是受歡迎的web

Vue-TypeScript-Cli

官方雖然明確提出對TypeScript的支持,可是並無明確的配置文檔,本身在配置的時候仍是須要查閱不少資料以及踩不少坑的(這個過程真的很藍瘦-_-)vue-router

可是如今能夠不用踩這個坑啦,我基於官方的vue-cli寫了一個vue-typescript-cli,能夠一鍵構建TypeScript模板

用法

vue init SimonZhangITer/vue-typescript-template <project-name>

好比

vue init SimonZhangITer/vue-typescript-template my-project

而後配置好的TypeScript模板就下載到./my-project文件夾了,npm run dev便可運行

TypeScript配置

這裏記錄一下當時的踩坑過程,全部配置已經在vue-typescript-template配置完畢

1. Webpack

安裝ts-loader

首先須要安裝ts-loader,這是TypeScript爲Webpack提供的編譯器,相似於babel-loader

npm i ts-loader -D

配置rules

接着在Webpack的module.rules裏面添加對ts的支持(我這裏的webpack版本是2.x):

{
    test: /\.vue$/,
    loader: 'vue-loader',
    options: vueLoaderConfig
},
{
    test: /\.ts$/,
    loader: 'ts-loader',
    options: {
      appendTsSuffixTo: [/\.vue$/],
    }
}

配置extensions

添加可識別文件後綴對ts的支持,如:

extensions: ['.js', '.vue', '.json', '.ts']

2. tsconfig.json

建立tsconfig.json文件,放在根目錄下,和package.json同級

配置內容主要也看我的需求,具體能夠去typescript的官網查看,可是有一點須要注意:

在Vue中,你須要引入 strict: true (或者至少 noImplicitThis: true,這是 strict 模式的一部分) 以利用組件方法中 this 的類型檢查,不然它會始終被看做 any 類型。

這裏列出個人配置,功能在註釋中給出

{
  "include": [
    "src/*",
    "src/**/*"
  ],
  "exclude": [
    "node_modules"
  ],
  "compilerOptions": {
    // types option has been previously configured
    "types": [
      // add node as an option
      "node"
    ],
    // typeRoots option has been previously configured
    "typeRoots": [
      // add path to @types
      "node_modules/@types"
    ],
    // 以嚴格模式解析
    "strict": true,
    // 在.tsx文件裏支持JSX
    "jsx": "preserve",
    // 使用的JSX工廠函數
    "jsxFactory": "h",
    // 容許從沒有設置默認導出的模塊中默認導入
    "allowSyntheticDefaultImports": true,
    // 啓用裝飾器
    "experimentalDecorators": true,
    "strictFunctionTypes": false,
    // 容許編譯javascript文件
    "allowJs": true,
    // 採用的模塊系統
    "module": "esnext",
    // 編譯輸出目標 ES 版本
    "target": "es5",
    // 如何處理模塊
    "moduleResolution": "node",
    // 在表達式和聲明上有隱含的any類型時報錯
    "noImplicitAny": true,
    "lib": [
      "dom",
      "es5",
      "es6",
      "es7",
      "es2015.promise"
    ],
    "sourceMap": true,
    "pretty": true
  }
}

3. 修改main.js

  1. 把項目主文件main.js修改爲main.ts,裏面的寫法基本不變,可是有一點須要注意:

引入Vue文件的時候須要加上.vue後綴,不然編輯器識別不到

  1. 把webpack的entry文件也修改爲main.ts

4. vue-shims.d.ts

TypeScript並不支持Vue文件,因此須要告訴TypeScript*.vue文件交給vue編輯器來處理。解決方案就是在建立一個vue-shims.d.ts文件,建議放在src目錄下再建立一個typings文件夾,把這個聲明文件放進去,如:src/typings/vue-shims.d.ts,文件內容:

*.d.ts類型文件不須要手動引入,TypeScript會自動加載
declare module '*.vue' {
  import Vue from 'vue'
  export default Vue
}

到這裏TypeScript在Vue中配置就完成了,能夠愉快的擼代碼了~

第三方插件庫

如今Vue官方已經明確提出支持TypeScript,並考慮出一個對應的vue-cli,在這以前,Vue開發團隊已經開發出了一些插件庫來支持TypeScript,這裏簡單和你們介紹一下。

Vue-Class-Component

vue-class-component是官方維護的TypeScript裝飾器,寫法比較扁平化。Vue對其作到完美兼容,若是你在聲明組件時更喜歡基於類的 API,這個庫必定不要錯過

ps:用了這個裝飾器以後寫方法不須要額外加逗號,賊嗨~~~

import Vue from "vue";
import Component from "vue-class-component";

@Component
export default class App extends Vue {
  name:string = 'Simon Zhang'

  // computed
  get MyName():string {
    return `My name is ${this.name}`
  }

  // methods
  sayHello():void {
    alert(`Hello ${this.name}`)
  }

  mounted() {
    this.sayHello();
  }
}

這個代碼若是用原生Vue語法來寫的話就是這樣:

export default {
  data () {
    return {
      name: 'Simon Zhang'
    }
  },

  mounted () {
    this.sayHello()
  },

  computed: {
    MyName() {
      return `My name is ${this.name}`
    }
  },

  methods: {
    sayHello() {
      alert(`Hello ${this.name}`)
    },
  }
}

Vuex-Class

vuex-class是基於基於vue-class-component對Vuex提供的裝飾器。它的做者同時也是vue-class-component的主要貢獻者,質量仍是有保證的。

import Vue from "vue";
import Component from "vue-class-component";
import { State, Action, Getter } from "vuex-class";

@Component
export default class App extends Vue {
  name:string = 'Simon Zhang'
  @State login: boolean;
  @Action initAjax: () => void;
  @Getter load: boolean;

  get isLogin(): boolean {
    return this.login;
  }

  mounted() {
    this.initAjax();
  }
}

上面的代碼就至關於:

export default {
  data() {
    return {
      name: 'Simon Zhang'
    }
  },

  mounted() {
    this.initAjax()
  },

  computed: {
    login() {
      return this.$store.state.login
    },
    load() {
      return this.$store.getters.load
    }
  },

  methods: {
    initAjax() {
      this.$store.dispatch('initAjax')
    }
  }
}

Vue-Property-Decorator

vue-property-decorator 是在 vue-class-component 上加強了更多的結合 Vue 特性的裝飾器,新增了這 7 個裝飾器

  • @Emit
  • @Inject
  • @Model
  • @Prop
  • @Provide
  • @Watch
  • @Component (從 vue-class-component 繼承)

引入部分第三方庫的時候須要額外聲明文件

好比說我想引入vue-lazyload,雖然已經在本地安裝,可是typescript仍是提示找不到模塊。緣由是typescript是從node_modules/@types目錄下去找模塊聲明,有些庫並無提供typescript的聲明文件,因此就須要本身去添加

解決辦法:在src/typings目前下建一個tools.d.ts文件,聲明這個模塊便可

declare module 'vue-awesome-swiper' {
  export const swiper: any
  export const swiperSlide: any
}

declare module 'vue-lazyload'

對vuex的支持不是很好

在TypeScript裏面使用不了mapState、mapGetters等方法,只能一個變量一個變量的去引用,這個要麻煩很多。不過使用vuex-class庫以後,寫法上也還算簡潔美觀

export default class modules extends Vue {
  @State login: boolean; // 對應this.$store.state.login
  @State headline: StoreState.headline[]; // 對應this.$store.state.headline

  private swiperOption: Object = {
    autoplay: true,
    loop: true,
    direction: "vertical"
  };

  logoClick(): void {
    alert("點我幹嗎");
  }
}

總結

TypeScript仍是很是值得學習和使用一個語言,仍是有不少優勢的

歡迎你們對個人項目提建議,歡迎Star~
項目地址:https://github.com/SimonZhang...

QQ交流羣:323743292

Build Setup

# 安裝依賴
npm install

# 啓動項目
npm run dev

# 打包項目
npm run build
相關文章
相關標籤/搜索