VUE - 在vue2項目中使TS語法


VUE - 在vue2項目中使TS語法

 

環境:vue2、vue-cli3 / vue-cli4 

 

並不是要把vue文件改為ts,而是可以在vue中寫ts語法

ts有什么用?

類型檢查、直接編譯到原生js、引入新的語法糖

為什么用ts?

TypeScript的設計目的應該是解決JavaScript的“痛點”:弱類型和沒有命名空間,導致很難模塊化,不適合開發大型程序。另外它還提供了一些語法糖來幫助大家更方便地實踐面向對象的編程。

typescript不僅可以約束我們的編碼習慣,還能起到注釋的作用,當我們看到一函數后我們立馬就能知道這個函數的用法,需要傳什么值,返回值是什么類型一目了然,對大型項目的維護性有很大的提升。也不至於使開發者搬起石頭砸自己的腳。

1、引入Typescript包

npm install vue-class-component vue-property-decorator --save npm install ts-loader typescript tslint tslint-loader tslint-config-standard --save-dev 
  • vue-class-component:擴展vue支持typescript,將原有的vue語法通過聲明的方式來支持ts

  • vue-property-decorator:基於vue-class-component擴展更多裝飾器

  • ts-loader:讓webpack能夠識別ts文件

  • tslint-loader:tslint用來約束文件編碼

  • tslint-config-standard: tslint 配置 standard風格的約束

2、配置

webpack配置

根據項目的不同配置的地方不同,如果是vue cli 3.0創建的項目需要在vue.config.js中配置,如果是3.0以下版本的話,需要webpack.base.conf中配置。(以下說明是在webpack.base.conf文件中更改)

2.1 在webpack.base.conf文件中更改

2.1.1. 在resolve.extensions中增加.ts,目的是在代碼中引入ts文件不用寫.ts后綴

  resolve: { extensions: ['.js', '.vue', '.json', '.ts'], alias: {} } 

2.2.2. 在module.rules中增加ts的rules

 module: { rules: [ { test: /\.ts$/, exclude: /node_modules/, enforce: 'pre', loader: 'tslint-loader' }, { test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, options: { appendTsSuffixTo: [/\.vue$/] } } ] } 

2.2.3. tsconfig.json配置
ts-loader會檢索文件中的tsconfig.json.以其中的規則來解析ts文件,詳細的配置可以參考https://www.tslang.cn/docs/handbook/tsconfig-json.html
我項目的tsconfig.json文件

{ // 編譯選項 "compilerOptions": { // 輸出目錄 "outDir": "./output", // 是否包含可以用於 debug 的 sourceMap "sourceMap": true, // 以嚴格模式解析 "strict": false, // 采用的模塊系統 "module": "esnext", // 如何處理模塊 "moduleResolution": "node", // 編譯輸出目標 ES 版本 "target": "es5", // 允許從沒有設置默認導出的模塊中默認導入 "allowSyntheticDefaultImports": true, // 將每個文件作為單獨的模塊 "isolatedModules": false, // 啟用裝飾器 "experimentalDecorators": true, // 啟用設計類型元數據(用於反射) "emitDecoratorMetadata": true, // 在表達式和聲明上有隱含的any類型時報錯 "noImplicitAny": false, // 不是函數的所有返回路徑都有返回值時報錯。 "noImplicitReturns": true, // 從 tslib 導入外部幫助庫: 比如__extends,__rest等 "importHelpers": true, // 編譯過程中打印文件名 "listFiles": true, // 移除注釋 "removeComments": true, "suppressImplicitAnyIndexErrors": true, // 允許編譯javascript文件 "allowJs": true, // 解析非相對模塊名的基准目錄 "baseUrl": "./", // 指定特殊模塊的路徑 "paths": { "jquery": [ "node_modules/jquery/dist/jquery" ] }, // 編譯過程中需要引入的庫文件的列表 "lib": [ "dom", "es2015", "es2015.promise" ] } } 

2.2.4. tslint.json配置
在目錄中新增tslint.json文件,由於我們前面安裝了tslint-config-standard,所以可以直接用tslint-config-standard中規則,文件如下:

  { "extends": "tslint-config-standard", "globals": { "require": true } } 
2.2 在vue.config.js文件中更改以下代碼即可
configureWebpack: { resolve: { extensions: [".ts", ".tsx", ".js", ".json"], alias: {} }, module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader', exclude: /node_modules/, options: { appendTsSuffixTo: [/\.vue$/], } } ] } }, 

3、讓項目識別.ts

由於 TypeScript 默認並不支持 *.vue 后綴的文件,所以在 vue 項目中引入的時候需要創建一個 vue-shim.d.ts 文件,放在根目錄下

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

4、vue組件的編寫

vue組件里大多數的方法改成通過@xxx(裝飾器)來表明當前定義的為什么數據。業務邏輯js的部分就可以直接采用ts的寫法了。

基本寫法

模板template和樣式style的寫法不變,script的模塊進行了改變,寫法如下:

<script lang="ts"> import { Component, Vue } from "vue-property-decorator"; @Component export default class Test extends Vue { }; </script> 
  • lang="ts"script聲明當前語言是ts
  • @Component:注明此類為一個vue組件
  • export default class Test extends Vue: export當前組件類是繼承vue的

data()中定義數據

data中的數據由原來的data()方法改成直接在對象中定義

export default class Test extends Vue { public message1: string = "heimayu"; public message2: string = "真好看"; } 

生命周期

 // 生命周期 private created(){ this.init(); } 

方法


    private init(){ console.log('halo'); } 

props傳值

props的話就沒有data那么舒服了,因為他需要使用裝飾器了,寫法如下

@Prop() propA:string @Prop() propB:number 

$emit傳值

不帶參數
  // 原來寫法:this.$emit('bindSend') // 現在直接寫 this.bindSend() // 多個定義 @Emit() bindSend():string{ return this.message } 
方法帶參數
  // 原來寫法:this.$emit('bindSend', msg) // 現在直接寫: this.bindSend(msg) // 多個下面的定義 @Emit() bindSend(msg:string){ // to do something } 
emit帶參數
  // 這里的test是改變組件引用的@事件名稱這時候要寫@test 而不是@bindSend2 @Emit('test') private bindSend2(){ return '這個可以用test接受'; } 

watch觀察數據

  // 原來的寫法 watch:{} @Watch('propA',{ deep:true }) test(newValue:string,oldValue:string){ console.log('propA值改變了' + newValue); } 

computed計算屬性

public get computedMsg(){ return '這里是計算屬性' + this.message; } public set computedMsg(message:string){ } 

完整代碼案例

<template> <div class="test-container"> {{message}} <input type="button" value="點擊觸發父級方法" @click="bindSend"/> <input type="button" value="點擊觸發父級方法" @click="handleSend"/> <input type="button" value="點擊觸發父級方法" @click="bindSend2"/> <!-- <Hello></Hello> --> </div> </template> <script lang="ts"> import { Component, Prop, Vue, Watch, Emit } from "vue-property-decorator"; import Hello from "./HelloWorld.vue"; // 注明此類為一個vue組件 @Component({ components: { Hello } }) export default class Test extends Vue { // 原有data中的數據在這里展開編寫 public message: string = "asd"; //原有props中的數據展開編寫 @Prop({ type: Number, default: 1, required: false }) propA?: number @Prop() propB:string //原有computed public get computedMsg(){ return '這里是計算屬性' + this.message; } public set computedMsg(message:string){ } //原有的watch屬性 @Watch('propA',{ deep:true }) public test(newValue:string,oldValue:string){ console.log('propA值改變了' + newValue); } // 以前需要給父級傳值的時候直接方法中使用emit就行了,當前需要通過emit來處理 @Emit() private bindSend():string{ return this.message } @Emit() private bindSend1(msg:string,love:string){ // 如果不處理可以不寫下面的,會自動將參數回傳 // msg += 'love'; // return msg; } //原有放在methods中的方法平鋪出來 public handleSend():void { this.bindSend1(this.message,'love'); } // 這里的emit中的參數是表明父級通過什么接受,類似以前的$emit('父級定義的方法') @Emit('test') private bindSend2(){ return '這個可以用test接受'; } } </script>
 

 

 

 

 

 

 

參考 :https://www.jianshu.com/p/3cbcdd766295

 

或 : https://blog.csdn.net/mouday/article/details/116653235

 


免責聲明!

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



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