vue-property-decorator Vue 属性装饰器
vue-class-component + vue-property-decorator
它们的区别与联系:
vue-property-decorator社区出品;
vue-class-component官方出品;
vue-class-component提供了Vue、Component等;
vue-property-decorator深度依赖了vue-class-component,拓展出了更多操作符:@Prop、 @PropSync、 @Model、 @ModelSync、 @Watch、 @Provide、 @Inject、 @ProvideReactive、 @InjectReactive、 @Emit、 @Ref、 @VModel、 @Component
在vue中引用使用
import {
Vue,
Component,
Prop,
PropSync,
Model,
ModelSync,
Watch,
Inject,
Provide,
ProvideReactive,
InjectReactive,
Emit,
Ref,
VModel
} from 'vue-property-decorator';
@Component
export default class YourComponent 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();
}
}
@Prop
单向数据流
所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。
@Prop(options: (PropOptions | Constructor[] | Constructor) = {})
@Prop装饰器接收一个参数,这个参数可以有三种写法:
1、PropOptions
:包含以下选项:type(类型), required(必填), default(默认值), validator(验证函数)
// 定义
type Prop<T> = { (): T } | { new(...args: any[]): T & object } | { new(...args: string[]): Function }
type PropType<T> = Prop<T> | Prop<T>[]
type PropValidator<T> = PropOptions<T> | PropType<T>
interface PropOptions<T = any> {
type?: PropType<T>;
required?: boolean;
default?: T | null | undefined | (() => T | null | undefined);
validator?(value: T): boolean;
}
// PropOptions 示例
{
type: Boolean, // 父组件传递给子组件的数据类型
required: false, // 是否必填
default: false // 默认值,如果传入的是 Object,则要 default: ()=>({}) 参数为函数
// 自定义验证函数
validator: value => ['success', 'warning', 'danger'].includes(value)
}
@Component
export default class YourComponent extends Vue {
@Prop({default: 'default value'}) readonly propB!: string;
@Prop({
type: Boolean, // 父组件传递给子组件的数据类型
required: false, // 是否必填
default: false // 默认值,如果传入的是 Object,则要 default: ()=>({}) 参数为函数
}) collapsed !: boolean;
}
2、Constructor[]
, 指定prop的可选类型;
@Component
export default class YourComponent extends Vue {
@Prop([String, Boolean]) readonly propC: string | boolean | undefined;
}
3、Constructor
,如String,Number,Boolean,Array,Object,Date,Function,Symbol或自定义函数类型等,指定prop的类型
@Component
export default class YourComponent extends Vue {
@Prop(Number) readonly propA: number | undefined;
}
完整示例
@Component
export default class YourComponent extends Vue {
@Prop(Number) readonly propA: number | undefined;
@Prop({default: 'default value'}) readonly propB!: string;
@Prop([String, Boolean]) readonly propC: string | boolean | undefined;
@Prop({
type: Boolean, // 父组件传递给子组件的数据类型
required: false, // 是否必填
default: false // 默认值,如果传入的是 Object,则要 default: ()=>({}) 参数为函数
}) collapsed !: boolean;
// <==>
// props: {
// propA: {
// type: Number
// },
// propB: {
// default: 'default value'
// },
// propC: {
// type: [String, Boolean]
// },
// collapsed: {
// type: Boolean,
// required: false,
// default: false
// }
// }
}
@PropSync
@PropSync @Prop 除了它将 propName 作为装饰器的参数之外,它的工作原理还类似于在幕后创建一个计算得到的 getter 和 setter。通过这种方式,您可以与属性进行交互,就好像它是一个常规数据属性一样,同时使它像.sync在父组件中附加修饰符一样简单
注意,使用@PropSync的时候是要在父组件配合.sync使用的
@PropSync(propName: string, options: (PropOptions | Constructor[] | Constructor) = {})
@PropSync和@Prop用法类似,二者区别在于:
@PropSync装饰器接受两个参数:
propName
: string类型,表示父组件传递过来的属性名;
options
: PropOptions | Constructor[] | Constructor 与@Prop中第一个参数一致;
@PropSync会生成一个新的计算属性
完整示例
@Component
export default class YourComponent extends Vue {
@PropSync('name', {type: String}) syncedName!: string;
// <==>
// props: {
// name: {
// type: String
// }
// },
// computed: {
// syncedName: {
// get() {
// return this.name
// },
// set(value) {
// this.$emit('update:name', value)
// }
// }
// }
}
@Model
自定义组件的 v-model
Vue.component('base-checkbox', {
model: {
prop: 'checked',
event: 'change'
},
props: {
checked: Boolean
},
template: `<input type="checkbox" v-bind:checked="checked" v-on:change="$emit('change', $event.target.checked)">`
});
定制prop和event,用作双向数据绑定
@Model(event?: string, options: (PropOptions | Constructor[] | Constructor) = {})
@Model装饰器允许我们在一个组件上自定义v-model,接受两个参数:
event
: string类型,表示事件名;
options
: PropOptions | Constructor[] | Constructor与@Prop
的第一个参数一致;
完整示例
@Component
export default class YourComponent extends Vue {
@Model('change', {type: Boolean}) readonly checked!: boolean;
// <==>
// model: { // 自定义组件的 v-model
// prop: 'checked',
// event: 'change'
// },
// props: {
// checked: {
// type: Boolean // Prop 验证
// }
// }
}
@ModelSync
@ModelSync(propName: string, event?: string, options: (PropOptions | Constructor[] | Constructor) = {})
@ModelSync
装饰器可接受三个参数:
propName
: string类型,表示类型名称;
event
: string类型,表示事件名;
options: PropOptions | Constructor[] | Constructor与@Prop的第一个参数一致;
完整示例
@Component
export default class YourComponent extends Vue {
@ModelSync('checked', 'change', {type: Boolean})
readonly checkedValue!: boolean;
// <==>
// model: {
// prop: 'checked',
// event: 'change'
// },
// props: {
// checked: {
// type: Boolean
// }
// },
// computed: {
// checkedValue: {
// get() {
// return this.checked
// },
// set(value) {
// this.$emit('change', value)
// }
// }
// }
}
@Watch
@Watch(path: string, options: WatchOptions = {})
@Watch装饰器接受两个参数:
path: string
类型,表示需要被监听的属性名;
options?: WatchOptions = {}
包含两个属性:
immediate?: boolean
监听开始后是否立即调用该回调函数;deep?: boolean
表示是否深度监
完整示例
interface Person {}
@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) {}
// <==>
// watch: {
// child: [
// {
// handler: 'onChildChanged',
// immediate: false,
// deep: false
// }
// ],
// person: [
// {
// handler: 'onPersonChanged1',
// immediate: true, // 子组件props首次获取到父组件传来的默认值时,也需要执行函数,此时就需要将immediate设为true
// deep: true // deep属性对对象进行深度监听
// }, {
// handler: 'onPersonChanged2',
// immediate: false,
// deep: false
// }
// ]
// },
// methods: {
// onChildChanged(val, oldVal) {},
// onPersonChanged1(val, oldVal) {},
// onPersonChanged2(val, oldVal) {}
// }
}
@Provide
provide 和 inject 绑定并不是可响应的,可用于深度嵌套的组件,而深层的子组件只需要父组件的部分内容时。
@Provide(key?: string | symbol)
完整示例
@Component
export default class YourComponent extends Vue {
// -> 父组件
@Provide() foo = 'foo';
@Provide('bar') baz = 'bar';
// <==>
// data() {
// return {
// foo: 'foo',
// baz: 'bar'
// }
// },
// provide() {
// return {
// foo: this.foo,
// bar: this.baz
// }
// }
}
@Inject
@Inject(options?: { from?: InjectKey, default?: any } | InjectKey)
完整示例
const symbol = Symbol('baz');
@Component
export default class YourComponent extends Vue {
// -> 子组件
@Inject() readonly foo!: string;
@Inject('bar') readonly bar!: string;
@Inject({from: 'optional', default: 'default'}) readonly optional!: string;
@Inject(symbol) readonly baz!: string;
// <==>
// inject: {
// foo: 'foo',
// bar: 'bar',
// optional: { from: 'optional', default: 'default' },
// baz: symbol
// }
}
@ProvideReactive
@Provide 的响应式版本 @ProvideReactive。
@ProvideReactive(key?: string | symbol)
完整示例
const key = Symbol()
@Component
export default class YourComponent extends Vue {
// -> 父组件
@ProvideReactive() one = 'value'
@ProvideReactive(key) two = 'value'
}
@InjectReactive
@Inject 的响应式版本 @InjectReactive。如果父组件修改了提供的值,则子组件可以捕获此修改
@InjectReactive(options?: { from?: InjectKey, default?: any } | InjectKey)
完整示例
const key = Symbol()
@Component
export default class YourComponent extends Vue {
// -> 子组件
@InjectReactive() one!: string
@InjectReactive(key) two!: string
}
@Emit
@Emit(event?: string)
@Emit装饰器接收一个可选参数,作为事件名;如果没有提供这个参数,$emit会将回调函数的camelCase(驼峰式)转为kebab-case(短横线命名),并将其作为事件名;
@Emit会将回调函数的返回值作为第二个参数,如果返回值是一个Promise对象,$emit会将Promise对象状态为resolved之后触发;
@Emit的回调函数的参数,会放在其返回值之后,一起被$emit当作参数使用;
完整示例
@Component
export default class YourComponent extends Vue {
count: number = 0;
@Emit()
addToCount(n: number) {
this.count += n;
}
@Emit('reset')
resetCount() {
this.count = 0;
}
@Emit()
returnValue() {
return 10;
}
@Emit()
onInputChange(e: any) {
return e.target.value;
}
@Emit()
promise() {
// 由@Emit $emit它们的返回值和它们的原始参数修饰的函数。如果返回值是一个promise,它会在发出之前被解析。
return new Promise((resolve) => {
setTimeout(() => {
resolve(20);
}, 0);
});
}
// <==>
// data() {
// return {
// count: 0
// }
// },
// methods: {
// addToCount(n) {
// this.count += n
// this.$emit('add-to-count', n)
// },
// resetCount() {
// this.count = 0
// this.$emit('reset')
// },
// returnValue() {
// this.$emit('return-value', 10)
// },
// onInputChange(e) {
// this.$emit('on-input-change', e.target.value, e)
// },
// promise() {
// const promise = new Promise((resolve) => {
// setTimeout(() => {
// resolve(20)
// }, 0)
// })
//
// promise.then((value) => {
// this.$emit('promise', value)
// })
// }
// }
}
@Ref
@Ref(refKey?: string)
// 加上 as HTMLDivElement 获取时:(不加会报错Object is possibly 'null'. 真是一波骚操作)
let docEl = document.documentElement as HTMLDivElement
完整示例
import AnotherComponent from '@/path/to/another-component.vue'
@Component
export default class YourComponent extends Vue {
@Ref() readonly anotherComponent!: AnotherComponent
@Ref('aButton') readonly button!: HTMLButtonElement;
// <==>
// computed() {
// anotherComponent: {
// cache: false, // 当 cache 缓存开启时,计算属性会使用缓存中的数据
// get() {
// return this.$refs.anotherComponent as AnotherComponent
// }
// },
// button: {
// cache: false,
// get() {
// return this.$refs.aButton as HTMLButtonElement
// }
// }
// }
}
@VModel
@VModel(propsArgs?: PropOptions)
完整示例
@Component
export default class YourComponent extends Vue {
@VModel({type: String}) names!: string;
// <==>
// props: {
// value: {
// type: String
// }
// },
// computed: {
// names: {
// get() {
// return this.value
// },
// set(value) {
// this.$emit('input', value)
// }
// }
// }
}
@Component
完整示例
@Component
export default class YourComponent extends Vue {
}