vue-property-decorator
主要提供了以下装饰器
- @Prop
- @PropSync
- @Model
- @Watch
- @Provide
- @Inject
- @ProvideReactive
- @InjectReactive
- @Emit
- @Ref
- @Component (由
vue-class-component
提供)
- Mixins (由
vue-class-component
提供)@Component
- Component装饰器它注明了此类为一个Vue组件,因此即使没有设置选项也不能省略
- 如果需要定义比如 name、components、filters、directives以及自定义属性,就可以在Component装饰器中定义,如下:
import {Component,Vue} from 'vue-property-decorator';
import {componentA,componentB} from '@/components';
@Component({
components:{
componentA,
componentB,
},
directives: {
focus: {
inserted: function (el) {
el.focus()
}
}
}
})
export default class YourCompoent extends Vue{
}
computed、data、methods
- 这里取消了组件的data和methods属性,以往data返回对象中的属性、methods中的方法需要直接定义在Class中,当做类的属性和方法
@Component
export default class HelloDecorator extends Vue {
count: number = 123
add(): number {
this.count + 1
}
get total(): number {
return this.count + 1
}
set total(param:number): void {
this.count = param
}
}
@props
- 组件接收属性的装饰器,如下使用:
import {Component,Vue,Prop} from vue-property-decorator;
@Component
export default class YourComponent extends Vue {
@Prop(String)
propA:string;
@Prop([String,Number])
propB:string|number;
@Prop({
type: String,
default: 'default value',
required: true,
validator: (value) => {
return [
'InProcess',
'Settled'
].indexOf(value) !== -1
}
})
propC:string;
}
@watch
- 实际就是Vue中的监听器,如下:
import { Vue, Component, Watch } from 'vue-property-decorator'
@Component
export default class YourComponent extends Vue {
@Watch('child')
onChildChanged(val: string, oldVal: string) {}
@Watch('person', { immediate: true, deep: true })
onPersonChanged1(val: Person, oldVal: Person) {}
@Watch('person')
onPersonChanged2(val: Person, oldVal: Person) {}
}
@emit
- vue-property-decorator 提供的 @Emit 装饰器就是代替Vue中的事件的触发$emit,如下:
import {Vue, Component, Emit} from 'vue-property-decorator';
@Component({})
export default class Some extends Vue{
mounted(){
this.$on('emit-todo', function(n) {
console.log(n)
})
this.emitTodo('world');
}
@Emit()
emitTodo(n: string){
console.log('hello');
}
}