目前在用vue开发的项目中,都会配合使用TypeScript进行一些约束。为了提高开发效率,往往会使用装饰器 来简化我们的代码。
本文主要介绍装饰器vue-property-decorator 和 vux-class 的使用。
1. 安装
npm i -S vue-property-decorator
npm i -S vuex-class
2. vue-property-decorator
@Component @Prop @PropSync @Model @ModelSync @Watch @Provide @Inject @ProvideReactive @InjectReactive @Emit @Ref @VModel
@Component
import { Vue, Component } from 'vue-property-decorator'
@Component({
components:{
componentA,
componentB,
}
})
export default class MyComponent extends Vue{
}
相当于:
export default{
name: 'MyComponent',
components:{
componentA,
componentB,
}
}
@Prop
@Prop(options: (PropOptions | Constructor[] | Constructor) = {}) decorator
表示:@Prop 装饰器接收一个参数,这个参数可以有三种写法:
- PropOptions:可以使用以下选项:type,required,default,validator
- Constructor:例如String,Number,Boolean等,指定 prop 的类型
- Constructor[]:指定 prop 的可选类型
例如:
import { Vue, Component, Prop } from 'vue-property-decorator'
@Component
export default class MyComponent extends Vue {
@Prop(Number) readonly propA: number | undefined
@Prop({ default: 'default value' }) readonly propB!: string
@Prop([String, Boolean]) readonly propC: string | boolean | undefined
}
相当于:
export default {
name: 'MyComponent',
props: {
propA: {
type: Number,
},
propB: {
default: 'default value',
},
propC: {
type: [String, Boolean],
},
},
@PropSync
@PropSync(propName: string, options: (PropOptions | Constructor[] | Constructor) = {}) decorator
- propName 表示父组件传递过来的属性名
- 父组件要结合
.sync 来使用
例如:
import { Vue, Component, PropSync } from 'vue-property-decorator'
@Component
export default class MyComponent extends Vue {
@PropSync('name', { type: String }) syncedName!: string
<template>
<div>
<MyComponent :name.sync="name" />
</div>
</template>
相当于:
export default {
name: 'MyComponent',
props: {
name: {
type: String,
},
},
computed: {
syncedName: {
get() {
return this.name
},
set(value) {
this.$emit('update:name', value)
},
},
},
}
@PropSync 的工作原理与@Prop 类似,除了接受propName作为装饰器的参数之外,它还在幕后创建了一个计算的getter和setter。通过这种方式,您可以像使用常规数据属性一样使用该属性,同时像在父组件中添加.sync 修饰符一样简单。
@Model
@Model 装饰器允许我们在一个组件上自定义v-model。
@Model(event?: string, options: (PropOptions | Constructor[] | Constructor) = {}) decorator
例如:
import { Vue, Component, Model } from 'vue-property-decorator'
@Component
export default class MyComponent extends Vue {
@Model('change', { type: Boolean }) readonly checked!: boolean
}
相当于:
export default {
model: {
prop: 'checked',
event: 'change',
},
props: {
checked: {
type: Boolean,
},
},
}
@ModelSync
@ModelSync(propName: string, event?: string, options: (PropOptions | Constructor[] | Constructor) = {}) decorator
例如:
import { Vue, Component, ModelSync } from 'vue-property-decorator'
@Component
export default class MyComponent extends Vue {
@ModelSync('checked', 'change', { type: Boolean }) readonly checkedValue!: boolean
}
相当于:
export default {
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 = {}) decorator
例如:
import { Vue, Component, Watch } from 'vue-property-decorator'
@Component
export default class MyComponent 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) {}
}
相当于:
export default {
watch: {
child: [
{
handler: 'onChildChanged',
immediate: false,
deep: false,
},
],
person: [
{
handler: 'onPersonChanged1',
immediate: true,
deep: true,
},
{
handler: 'onPersonChanged2',
immediate: false,
deep: false,
},
],
},
methods: {
onChildChanged(val, oldVal) {},
onPersonChanged1(val, oldVal) {},
onPersonChanged2(val, oldVal) {},
},
}
@Provide | @Inject
@Provide(key?: string | symbol) decorator
@Inject(options?: { from?: InjectKey, default?: any } | InjectKey) decorator
例如:
import { Component, Inject, Provide, Vue } from 'vue-property-decorator'
const symbol = Symbol('baz')
@Component
export class MyComponent extends Vue {
@Inject() readonly foo!: string
@Inject('bar') readonly bar!: string
@Inject({ from: 'optional', default: 'default' }) readonly optional!: string
@Inject(symbol) readonly baz!: string
@Provide() foo = 'foo'
@Provide('bar') baz = 'bar'
}
相当于:
const symbol = Symbol('baz')
export const MyComponent = Vue.extend({
inject: {
foo: 'foo',
bar: 'bar',
optional: { from: 'optional', default: 'default' },
baz: symbol,
},
data() {
return {
foo: 'foo',
baz: 'bar',
}
},
provide() {
return {
foo: this.foo,
bar: this.baz,
}
},
})
@ProvideReactive | @InjectReactive
它们是@provider 和@Inject 的响应式版本。如果父组件修改了提供的值,那么子组件可以捕捉到这种修改。
@ProvideReactive(key?: string | symbol) decorato
@InjectReactive(options?: { from?: InjectKey, default?: any } | InjectKey) decorator
例如:
const key = Symbol()
@Component
class ParentComponent extends Vue {
@ProvideReactive() one = 'value'
@ProvideReactive(key) two = 'value'
}
@Component
class ChildComponent extends Vue {
@InjectReactive() one!: string
@InjectReactive(key) two!: string
}
@Emit
@Emit(event?: string) decorator
例如:
import { Vue, Component, Emit } from 'vue-property-decorator'
@Component
export default class MyComponent extends Vue {
count = 0
@Emit()
addToCount(n: number) {
this.count += n
}
@Emit('reset')
resetCount() {
this.count = 0
}
@Emit()
returnValue() {
return 10
}
@Emit()
onInputChange(e) {
return e.target.value
}
@Emit()
promise() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(20)
}, 0)
})
}
}
相当于:
export default {
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) decorator
例如:
import { Vue, Component, Ref } from 'vue-property-decorator'
import AnotherComponent from '@/path/to/another-component.vue'
@Component
export default class MyComponent extends Vue {
@Ref() readonly anotherComponent!: AnotherComponent
@Ref('aButton') readonly button!: HTMLButtonElement
}
相当于:
export default {
computed() {
anotherComponent: {
cache: false,
get() {
return this.$refs.anotherComponent as AnotherComponent
}
},
button: {
cache: false,
get() {
return this.$refs.aButton as HTMLButtonElement
}
}
}
}
@VModel
@VModel(propsArgs?: PropOptions) decorator
例如:
import { Vue, Component, VModel } from 'vue-property-decorator'
@Component
export default class MyComponent extends Vue {
@VModel({ type: String }) name!: string
}
相当于:
export default {
props: {
value: {
type: String,
},
},
computed: {
name: {
get() {
return this.value
},
set(value) {
this.$emit('input', value)
},
},
},
}
3. vuex-class
@State @Getter @Action @Mutation namespace
import Vue from 'vue'
import Component from 'vue-class-component'
import {
State,
Getter,
Action,
Mutation,
namespace
} from 'vuex-class'
const someModule = namespace('path/to/module')
@Component
export class MyComponent extends Vue {
@State('foo') stateFoo
@State(state => state.bar) stateBar
@Getter('foo') getterFoo
@Action('foo') actionFoo
@Mutation('foo') mutationFoo
@someModule.Getter('foo') moduleGetterFoo
@State foo
@Getter bar
@Action baz
@Mutation qux
created () {
this.stateFoo
this.stateBar
this.getterFoo
this.actionFoo({ value: true })
this.mutationFoo({ value: true })
this.moduleGetterFoo
}
}
|