vue-class-component
为了定义带有装饰器风格的Vue组件,如果使用Babel转换,必须使用babel-plugin-transform-decorators-legacy 包
如果使用ts编写,--experimentalDecorators 设置为true
vue-class-component 提供mixins方法
//mixin.js
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export clas MyMixin extends Vue {
mixinValue = 'Hello'
}
引入mixin.js
import Component, { mixins } from 'vue-class-component'
import MyXin from './mixin.js'
@Component
export class MyComp extends mixins(MyXin) {
created() {
console.log(this.mixinValue) // Hello
}
}
创建自定义装饰器
vue-class-component 提供createDecorator 方法创建自定义装饰器
//decorators.js
import { createDecorator } from 'vue-class-component'
export const NoCache = createDecorator((options, key) => {
options.computed[key].cache = false
})
import { NoCache } from './decorators'
@Component
class MyComp extends Vue {
@NoCache
get random() {
return Math.random()
}
}
增加自定义钩子
如果你使用像Vue-router 一样的插件,想在组件里使用它们提供的钩子,registerHooks方法可以实现
//class-component-hooks.js
import Component from 'vue-class-component'
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()
}
beoferRouteLeave(to, from, next) {
console.log('beforeRouteLeave')
next()
}
}
插件钩子需在你定义组件的时候优先执行
//main.js
import './class-component-hooks'
import Vue from 'vue'
import MyComp fron './MyComp'
new Vue({
el: '#app',
components: {
MyComp
}
})
⚠️注意:
1、this 变量箭头函数绑定父级域,但在Component装饰器中这么使用会报错
@Component
class MyComp extends Vue {
foo = 123
bar = () => {
this.foo = 456 //this 已经不在vue的实例了
}
}
你可以直接使用,因为Vue已经将this自动绑定了
@Component
class MyComp extends Vue {
foo = 123
bar() {
this.foo = 456 //Vue已经将this自动绑定了
}
}
2、变量定义为undefined,无法被Vue进行数据监控
@Component
class MyComp extends Vue {
foo = undefined //无效
bar = null //有效
data() {
retuen {
baz : undefined // 有效
}
}
}
网友评论