一庐完、首先 下載
npm install vue-class-component vue-property-decorator --save-dev
二、vue-class-component 和 vue-property-decorator 的區(qū)別與聯(lián)系
vue-property-decorator社區(qū)出品鸿市;vue-class-component官方出品
vue-class-component提供了Vue、Component等浙芙;
vue-property-decorator深度依賴了vue-class-component喜命,拓展出了更多操作符:@Prop、@Emit乾蓬、@Inject惠啄、@Model、@Provide巢块、@Watch礁阁;
三 、開發(fā)時正常引入vue-property-decorator就行
1. 引入后寫vue代碼就是如此族奢,
import {Component, Prop, Vue} from 'vue-property-decorator'
@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();
}
}
相當于
export default {
data () {
return {
name: 'Simon Zhang'
}
},
mounted () {
this.sayHello()
},
computed: {
MyName() {
return `My name is ${this.name}`
}
},
methods: {
sayHello() {
alert(`Hello ${this.name}`)
},
}
}
四、總結(jié)
1丹鸿、寫法問題:引入組件和接收父組件傳過來的參數(shù)
@Component({
components: {
XXXX
},
props: {
mapFlag: Number
}
})
2越走、獲取refs,在其后面加上as HTMLDivElement(不知道是不是這插件引起的靠欢,懶得管廊敌,直接干就是)
let layoutList:any = this.$refs.layout as HTMLDivElement
或
let fieldCalculate:any = (this as any).$refs.fieldCalculate
3、ts文件 公用方法導(dǎo)出
const xxx = (value: any, type: string) => {
...
}
export { xxx, xxx, xxx, xxx }
4门怪、引入裝飾器骡澈,使用方式@Watch
import { Component, Prop, Watch, Emit } from 'vue-property-decorator'
5、引用插件掷空。在shims-vue.d.ts 文件中聲明肋殴,再在組件中引用
declare module 'vuedraggable' {
const vuedraggable: any;
export default vuedraggable;
}
6、@Watch使用
// 監(jiān)聽formula 其變化則顯示驗證公式按鈕
@Watch('formula', { deep: true, immediate: true }) formulaWatch (newVal:string, oldVal:string) {
if (newVal !== oldVal) {
this.grammarSuccess = true
this.errMsgFlag = false
this.checkFormulaSuccess = false
}
}
7坦弟、計算屬性方法寫法(跟@watch一樣护锤,當成方法寫就行;加一個關(guān)鍵字get)
get aTagDatasFcomput () {
// computed計算屬性酿傍, 過濾出visible為true的對象來渲染烙懦,
因為當 v-if 與 v-for 一起使用時,v-for 具有比 v-if 更高的優(yōu)先級赤炒,這意味著 v-if 將分別重復(fù)運行于每個 v-for 循環(huán)中
return this.aTagDatasF.filter(item => item.visible)
}
8氯析、@Prop的用法
@Prop({
type: Boolean, // 父組件傳遞給子組件的數(shù)據(jù)類型
required: false, // 是否必填
default: false // 默認值亏较, 如果傳入的是 Object,則要 default: ()=>({}) 參數(shù)為函數(shù)
}) collapsed !: boolean
@Prop()private datas!: any
感嘆號是非null和非undefined的類型斷言掩缓,所以上面的寫法就是對datas這個屬性進行非空斷言
9宴杀、ts設(shè)置html的fontSize
let docEl = document.documentElement as HTMLDivElement // 加上 as HTMLDivElement
獲取時:(不加會報錯Object is possibly 'null'. 真是一波騷操作)