vue-class-component 是尤大大推出的vue對typescript支持的裝飾器(庫)vue
vue-class-component強調了幾點用法:git
<script>
import Vue from 'vue'
import Component from 'vue-class-component'
@Component({
props: {
propMessage: String
}
})
export default class App extends Vue {
// 初始化數據 data能夠聲明成類屬性形式
msg = 123
// 使用props
helloMsg = 'Hello, ' + this.propMessage
// 生命週期鉤子聲明 保留名稱
mounted () {
this.greet()
}
// computed屬性能夠聲明成類方法形式
get computedMsg () {
return 'computed ' + this.msg
}
// method方法能夠聲明成類方法形式
greet () {
alert('greeting: ' + this.msg)
}
}
</script>
複製代碼
createDecorator能夠自定義裝飾器,須要接受一個回調函數做爲第一個參數,包括如下幾個參數github
// 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屬性不會再被緩存
@NoCache
get random () {
return Math.random()
}
}
複製代碼
自定義鉤子vue-router
// class-component-hooks.js
import Component from 'vue-class-component'
// 註冊鉤子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
}
}
複製代碼
this爲undefined, 本來使用箭頭函數的this實際上指向的是vue實例, 可是將箭頭函數定義爲類屬性並在其中訪問它,則它將不起做用,this指向的是vue實例的代理typescript
@Component
class MyComp extends Vue {
foo = 123
bar = () => {
this.foo = 456
}
}
複製代碼
只要將函數定義爲方法,就會自動生成vue實例緩存
@Component
class MyComp extends Vue {
foo = 123
bar () {
// Correctly update the expected property.
this.foo = 456
}
}
複製代碼
對於一些屬性的初始值應該用null或者data鉤子進行處理bash
@Component
class MyComp extends Vue {
// 不會進行處理
foo = undefined
// 會進行處理
bar = null
data () {
return {
// 會進行處理
baz: undefined
}
}
}
複製代碼