如果想要在 vue2.0 中使用ts語法,需要引用 vue-property-decorator 這個第三方js庫
此組件基本依賴於 vue-class-component 用於以下屬性:
- @Component (完全繼承於
vue-class-component
) - @Emit
- @Inject
- @Provice
- @Prop
- @Watch
- @Model
一.安裝
npm install --save vue-property-decorator
二. ts頁面中基本寫法
import { Component, Vue, Inject } from "vue-property-decorator"; @Component({ components: {} }) export default class SubjectList extends Vue { dialogVisible: boolean = false; storageVisible: boolean = false; config: any = { style: "table-form", queryUrl: "Subject/GetAll", isCustom: true, params: {} }; created() { } }
可以看到,這里的變量,與鈎子都屬於同級,會少些一些代碼
三.下面講幾個用的較多的幾個屬性
1.組件引用
import { Component, Vue, Inject } from "vue-property-decorator"; import addSelectProduct from "../../coupon/components/addSelectProduct/addSelectProduct.component.vue"; @Component({ components: { addSelectProduct, } }) export default class SubjectList extends Vue { dialogVisible: boolean = false; storageVisible: boolean = false; config: any = { style: "table-form", queryUrl: "Subject/GetAll", isCustom: true, params: {} }; created() { } }
2. watch 監聽屬性
import { Component, Vue, Inject,Watch } from "vue-property-decorator"; @Component({ components: {} }) export default class SubjectList extends Vue { dialogVisible: boolean = false; storageVisible: boolean = false; config: any = { style: "table-form", queryUrl: "Subject/GetAll", isCustom: true, params: {} }; productList: any = [] // 監聽屬性 @Watch("dialogVisible") onCountChanged(val: any, oldVal: any) { console.log(val); }// 監聽屬性 @Watch("productList",{ deep: true }) onCountChanged2(val: any, oldVal: any) { console.log(val); } created() { } }
- 通過引用 Watch, @watch()中第一個參數為: 監聽的屬性名, 第二個參數為可選對象(可用來監聽對象,數組復雜類型)
- 當監聽多個屬性值時, 同法往下累加, 注意:定義監聽函數的名字不能相同,如上例:onCountChanged 和 onCountChanged2
3.計算屬性
import { Component, Vue, Inject } from "vue-property-decorator"; @Component({ components: {} }) export default class SubjectList extends Vue { dialogVisible: boolean = false; storageVisible: boolean = false; config: any = { style: "table-form", queryUrl: "Subject/GetAll", isCustom: true, params: {} }; limitType : number = 0 // 計算屬性 get shouldEdit() { return !router.currentRoute.query.id; } get getButtonName() { let type: any = { 1: '拼團', 2: '限時折扣', }; return type[this.limitType]; } created() { } }
- 使用時只需以 get 開頭 + 方法 + 有返回值
4. 混入公共方法 mixins
import { Component, Vue, Inject } from "vue-property-decorator"; import PublicMethod from '@/plugins/mixins/provides/service/publicMethod'; @Component({ components: {}, mixins:[PublicMethod] }) export default class SubjectList extends Vue { dialogVisible: boolean = false; storageVisible: boolean = false; config: any = { style: "table-form", queryUrl: "Subject/GetAll", isCustom: true, params: {} }; created() { (<any>this).WxShare({ infoId : this.config.params.id , infoType : 7 }); } }
分享一刻: