Vue裝飾器中的vue-property-decorator?和?vux-class使用詳解
目前在用vue開(kāi)發(fā)的項(xiàng)目中,都會(huì)配合使用TypeScript進(jìn)行一些約束。為了提高開(kāi)發(fā)效率,往往會(huì)使用裝飾器來(lái)簡(jiǎn)化我們的代碼。
本文主要介紹裝飾器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{
}
相當(dāng)于:
export default{
name: 'MyComponent',
components:{
componentA,
componentB,
}
}
@Prop
@Prop(options: (PropOptions | Constructor[] | Constructor) = {}) decorator表示:@Prop裝飾器接收一個(gè)參數(shù),這個(gè)參數(shù)可以有三種寫法:
- PropOptions:可以使用以下選項(xiàng):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
}
相當(dāng)于:
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 表示父組件傳遞過(guò)來(lái)的屬性名
- 父組件要結(jié)合
.sync來(lái)使用
例如:
// child.vue
import { Vue, Component, PropSync } from 'vue-property-decorator'
@Component
export default class MyComponent extends Vue {
@PropSync('name', { type: String }) syncedName!: string
<!-- parent.vue -->
<template>
<div>
<MyComponent :name.sync="name" />
</div>
</template>
相當(dāng)于:
export default {
name: 'MyComponent',
props: {
name: {
type: String,
},
},
computed: {
syncedName: {
get() {
return this.name
},
set(value) {
this.$emit('update:name', value)
},
},
},
}
@PropSync的工作原理與@Prop類似,除了接受propName作為裝飾器的參數(shù)之外,它還在幕后創(chuàng)建了一個(gè)計(jì)算的getter和setter。通過(guò)這種方式,您可以像使用常規(guī)數(shù)據(jù)屬性一樣使用該屬性,同時(shí)像在父組件中添加.sync修飾符一樣簡(jiǎn)單。
@Model
@Model裝飾器允許我們?cè)谝粋€(gè)組件上自定義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
}
相當(dāng)于:
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
}
相當(dāng)于:
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) {}
}
相當(dāng)于:
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'
}
相當(dāng)于:
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的響應(yīng)式版本。如果父組件修改了提供的值,那么子組件可以捕捉到這種修改。
@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)
})
}
}
相當(dāng)于:
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
}
相當(dāng)于:
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
}
相當(dāng)于:
export default {
props: {
value: {
type: String,
},
},
computed: {
name: {
get() {
return this.value
},
set(value) {
this.$emit('input', value)
},
},
},
}
3. vuex-class
@State@Getter@Action@Mutationnamespace
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
// 如果省略參數(shù), 直接使用每一個(gè) state/getter/action/mutation 類型的屬性名稱
@State foo
@Getter bar
@Action baz
@Mutation qux
created () {
this.stateFoo // -> store.state.foo
this.stateBar // -> store.state.bar
this.getterFoo // -> store.getters.foo
this.actionFoo({ value: true }) // -> store.dispatch('foo', { value: true })
this.mutationFoo({ value: true }) // -> store.commit('foo', { value: true })
this.moduleGetterFoo // -> store.getters['path/to/module/foo']
}
}
到此這篇關(guān)于Vue裝飾器中的vue-property-decorator 和 vux-class使用詳解的文章就介紹到這了,更多相關(guān)vue-property-decorator 和 vux-class內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue項(xiàng)目中vue-echarts講解及常用圖表實(shí)現(xiàn)方案(推薦)
這篇文章主要介紹了vue項(xiàng)目中vue-echarts講解及常用圖表方案實(shí)現(xiàn),主要針對(duì)代碼示例中的內(nèi)容進(jìn)行問(wèn)題講解,詳細(xì)代碼在文章中給大家提到,需要的朋友可以參考下2022-09-09
vue 父組件通過(guò)$refs獲取子組件的值和方法詳解
今天小編就為大家分享一篇vue 父組件通過(guò)$refs獲取子組件的值和方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
vue實(shí)現(xiàn)路由跳轉(zhuǎn)動(dòng)態(tài)title標(biāo)題信息
這篇文章主要介紹了vue實(shí)現(xiàn)路由跳轉(zhuǎn)動(dòng)態(tài)title標(biāo)題信息,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
在vue中使用export?default導(dǎo)出的class類方式
這篇文章主要介紹了在vue中使用export?default導(dǎo)出的class類方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
分享一個(gè)vue項(xiàng)目“腳手架”項(xiàng)目的實(shí)現(xiàn)步驟
這篇文章主要介紹了分享一個(gè)vue項(xiàng)目“腳手架”項(xiàng)目的實(shí)現(xiàn)步驟,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-05-05
Vue.js 無(wú)限滾動(dòng)列表性能優(yōu)化方案
這篇文章主要介紹了Vue.js 無(wú)限滾動(dòng)列表性能優(yōu)化方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12

