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風格的約束
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"
]
}
}
完整代碼
<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.cnblogs.com/webhmy/p/13690836.html