vue-class-component 是尤大大推出的vue對(duì)typescript支持的裝飾器(庫(kù))
vue-class-component強(qiáng)調(diào)了幾點(diǎn)用法:
1、methods可以直接聲明為類(lèi)成員方法
2凡涩、computed屬性可以聲明為類(lèi)屬性訪問(wèn)器
3、data數(shù)據(jù)可以聲明為類(lèi)屬性
4事格、data render 和所有Vue生命周期掛鉤也可以直接聲明為類(lèi)成員方法热幔,但不能在實(shí)例本身上調(diào)用它們殖氏。在聲明自定義方法時(shí)蛉谜,應(yīng)避免使用這些保留名稱(chēng)稚晚。
使用方法
官網(wǎng)demo
<script>
import Vue from 'vue'
import Component from 'vue-class-component'
@Component({
props: {
propMessage: String
}
})
export default class App extends Vue {
// 初始化數(shù)據(jù) data可以聲明成類(lèi)屬性形式
msg = 123
// 使用props
helloMsg = 'Hello, ' + this.propMessage
// 生命周期鉤子聲明 保留名稱(chēng)
mounted () {
this.greet()
}
// computed屬性可以聲明成類(lèi)方法形式
get computedMsg () {
return 'computed ' + this.msg
}
// method方法可以聲明成類(lèi)方法形式
greet () {
alert('greeting: ' + this.msg)
}
}
</script>
createDecorator
createDecorator可以自定義裝飾器,需要接受一個(gè)回調(diào)函數(shù)作為第一個(gè)參數(shù)型诚,包括以下幾個(gè)參數(shù)
options:對(duì)象參數(shù)客燕, key ,paramsIndex
// decorators.js
import { createDecorator } from 'vue-class-component'
export const NoCache = createDecorator((options, key) => {
// component options should be passed to the callback
// and update for the options object affect the component
options.computed[key].cache = false
})
import { NoCache } from './decorators'
@Component
class MyComp extends Vue {
// computed屬性不會(huì)再被緩存
@NoCache
get random () {
return Math.random()
}
}
Component.registerHooks
自定義鉤子
// class-component-hooks.js
import Component from 'vue-class-component'
// 注冊(cè)鉤子name
Component.registerHooks([
'beforeRouteEnter',
'beforeRouteLeave',
'beforeRouteUpdate' // for vue-router 2.2+
])
// MyComp.js
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
class MyComp extends Vue {
beforeRouteEnter (to, from, next) {
console.log('beforeRouteEnter')
next() // needs to be called to confirm the navigation
}
beforeRouteLeave (to, from, next) {
console.log('beforeRouteLeave')
next() // needs to be called to confirm the navigation
}
}
箭頭函數(shù)
this為undefined,
原本使用箭頭函數(shù)的this實(shí)際上指向的是vue實(shí)例,
但是將箭頭函數(shù)定義為類(lèi)屬性并在其中訪問(wèn)它狰贯,則它將不起作用也搓,this指向的是vue實(shí)例的代理
@Component
class MyComp extends Vue {
foo = 123
bar = () => {
this.foo = 456
}
}
只要將函數(shù)定義為方法赏廓,就會(huì)自動(dòng)生成vue實(shí)例
@Component
class MyComp extends Vue {
foo = 123
bar () {
// Correctly update the expected property.
this.foo = 456
}
}
類(lèi)屬性的undefined沒(méi)有做出處理
對(duì)于一些屬性的初始值應(yīng)該用null或者data鉤子進(jìn)行處理
@Component
class MyComp extends Vue {
// 不會(huì)進(jìn)行處理
foo = undefined
// 會(huì)進(jìn)行處理
bar = null
data () {
return {
// 會(huì)進(jìn)行處理
baz: undefined
}
}
}