vue-property-decorator使用指南

在Vue中使用TypeScript时,非常好用的一个库,使用装饰器来简化书写。

一、安装

npm i -S vue-property-decorator

二、用法

1、@Component(options:ComponentOptions = {})

@Component 装饰器可以接收一个对象作为参数,可以在对象中声明 components ,filters,directives 等未提供装饰器的选项

虽然也可以在 @Component 装饰器中声明 computed,watch 等,但并不推荐这么做,因为在访问 this 时,编译器会给出错误提示

即使没有组件也不能省略@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{
   
}

2、@Prop(options: (PropOptions | Constructor[] | Constructor) = {}) 

父子组件之间值的传递

@Prop 装饰器接收一个参数,这个参数可以有三种写法:

  • Constructor ,例如 String,Number,Boolean 等,指定 prop 的类型;
  • Constructor[] ,指定 prop 的可选类型;
  • PropOptions ,可以使用以下选项: type,default,required,validator 。

 

import { Vue, Component, Prop } from 'vue-property-decorator'

@Componentexport default class MyComponent extends Vue {

 @Prop(String) propA: string | undefined

 @Prop([String, Number]) propB!: string | number

 @Prop({

 type: String,

 default: 'abc'

 })

 propC!: string

}

等同于下面的 js 写法

export default {
    props: {
        propA: {
            type: Number
        },
        propB: {
            default: 'default value'
        },

        propC: {
            type: [String, Boolean]
        }
    }
}

注意:

  • 属性的ts类型后面需要加上 undefined 类型;或者在属性名后面加上!,表示 非null 和 非undefined的断言,否则编译器会给出错误提示;
  • 指定默认值必须使用上面例子中的写法,如果直接在属性名后面赋值,会重写这个属性,并且会报错。

3、@PropSync(propName: string, options: (PropOptions | Constructor[] | Constructor) = {})

  • @PropSync 装饰器与 @prop 用法类似,二者的区别在于:
  • @PropSync 装饰器接收两个参数: 

propName: string 表示父组件传递过来的属性名; 

options: Constructor | Constructor[] | PropOptions 与 @Prop 的第一个参数一致;

@PropSync 会生成一个新的计算属性。

import { Vue, Component, PropSync } from 'vue-property-decorator'

@Component

export default class MyComponent extends Vue {

 @PropSync('propA', { type: String, default: 'abc' }) syncedPropA!: string

}

等同于下面的 js 写法

export default {

 props: {
     propA: {
         type: String,
         default: 'abc'
     }
 },

 computed: {
     syncedPropA: {
        get() {
            return this.propA
        },
        set(value) {
            this.$emit('update:propA', value)
        }
     }
 }
}

注意: @PropSync 需要配合父组件的 .sync 修饰符使用

 

在说vue 修饰符sync前,我们先看下官方文档:vue .sync 修饰符,里面说vue .sync 修饰符以前存在于vue1.0版本里,但是在在 2.0 中移除了 .sync 。但是在 2.0 发布之后的实际应用中,我们发现 .sync 还是有其适用之处,比如在开发可复用的组件库时。我们需要做的只是让子组件改变父组件状态的代码更容易被区分。从 2.3.0 起我们重新引入了 .sync 修饰符,但是这次它只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 监听器。
示例代码如下:

<comp :foo.sync="bar"></comp>

会被扩展为:

<comp :foo="bar" @update:foo="val => bar = val"></comp>

当子组件需要更新 foo 的值时,它需要显式地触发一个更新事件:

this.$emit('update:foo', newValue)

4、@Model(event?: string, options: (PropOptions | Constructor[] | Constructor) = {})

@Model 装饰器允许我们在一个组件上自定义 v-model ,接收两个参数:

event: string 事件名。

options: Constructor | Constructor[] | PropOptions 与 @Prop 的第一个参数一致。

import { Vue, Component, Model } from 'vue-property-decorator'

@Component

export default class MyInput extends Vue {

 @Model('change', { type: String, default: '123' }) value!: string

}

等同于下面的 js 写法

export default {
    model: {
        prop: 'value',
        event: 'change'
    },
    props: {
        value: {
            type: String,
            default: '123'
        }
    }
}

上面例子中指定的是 change 事件,所以我们还需要在 template 中加上相应的事件:

<template>

 <input

 type="text"

 :value="value"

 @change="$emit('change', $event.target.value)"

 />

</template>

对 自定义v-model 不太理解的同学,可以查看 自定义事件

 

5、@Watch(path: string, options: WatchOptions = {})

@Watch 装饰器接收两个参数:

path: string 被侦听的属性名;
options?: WatchOptions={} options 可以包含两个属性 :

immediate?:boolean 侦听开始之后是否立即调用该回调函数;

deep?:boolean 被侦听的对象的属性被改变时,是否调用该回调函数;

侦听开始,发生在 beforeCreate 勾子之后, created 勾子之前

import { Vue, Component, Watch } from 'vue-property-decorator'

@Component

export default class MyInput extends Vue {

 @Watch('msg')

 onMsgChanged(newValue: string, oldValue: string) {}



 @Watch('arr', { immediate: true, deep: true })

 onArrChanged1(newValue: number[], oldValue: number[]) {}



 @Watch('arr')

 onArrChanged2(newValue: number[], oldValue: number[]) {}

}

等同于下面的 js 写法

export default {
    watch: {
        msg: [
          {
            handler: 'onMsgChanged',
            immediate: false,
            deep: false
          }
        ],
        arr: [
          {
            handler: 'onArrChanged1',
            immediate: true,
            deep: true
          },
          {
            handler: 'onArrChanged2',
            immediate: false,
            deep: false
          }
        ]
    },
    methods: {
        onMsgVhanged(newValue, oldValue) {},
        onArrChange1(newValue, oldValue) {},
        onArrChange2(newValue, oldValue) {}
    }
}

6、@Emit(event?: string)

  • @Emit 装饰器接收一个可选参数,该参数是 $Emit 的第一个参数,充当事件名。如果没有提供这个参数, $Emit 会将回调函数名的 camelCase 转为 kebab-case ,并将其作为事件名;
  • @Emit 会将回调函数的返回值作为第二个参数,如果返回值是一个 Promise 对象, $emit 会在 Promise 对象被标记为 resolved 之后触发;
  • @Emit 的回调函数的参数,会放在其返回值之后,一起被 $emit 当做参数使用。
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)
    })
 }
}

等同于下面的 js 写法

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)

 })

 }

 }

}

7、@Ref(refKey?: string)

@Ref 装饰器接收一个可选参数,用来指向元素或子组件的引用信息。如果没有提供这个参数,会使用装饰器后面的属性名充当参数

import { Vue, Component, Ref } from 'vue-property-decorator'

import { Form } from 'element-ui'

@Componentexport default class MyComponent extends Vue {

 @Ref() readonly loginForm!: Form

 @Ref('changePasswordForm') readonly passwordForm!: Form

 public handleLogin() {

     this.loginForm.validate(valide => {

         if (valide) {

             // login...

         } else {

             // error tips

         }

     })

 }

}

等同于下面的 js 写法

export default {

 computed: {

 loginForm: {

 cache: false,

 get() {

 return this.$refs.loginForm

 }

 },

 passwordForm: {

 cache: false,

 get() {

 return this.$refs.changePasswordForm

 }

 }

 }

}

@Provide/@Inject 和 @ProvideReactive/@InhectReactive

由于平时基本不用到provide/inject选项,暂时先放着,之后再补充

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: vue-property-decorator 是一个用于简化 Vue.js 组件开发的装饰器库,而 Vue 3 是 Vue.js 的下一个主要版本。vue-property-decorator 目前仅适用于 Vue 2.x 版本,并在 Vue 3.x 中不再兼容。 Vue 3 意味着对 Vue.js 进行了大规模重写和重构,旨在提供更高性能、更小的包大小、更好的开发体验和更多功能。Vue 3 引入了许多新特性,例如 Composition API、Teleport、Suspense 等。 由于 Vue 3 中改编了大量的底层代码,vue-property-decoratorVue 3.x 中不再适用,这是因为 Vue 3 在其组件定义和交互方式上引入了一些改变。为了使现有的代码能够在 Vue 3.x 中运行,我们需要采用其他方式来替代 vue-property-decorator,用于装饰 Vue 组件的功能。 Vue 3 中提供了一种新的组合式 API - Composition API,它允许我们使用函数的形式组织和复用逻辑。通过 Composition API,我们可以在 Vue 组件中按照逻辑功能划分代码,使得组件更加清晰和可维护。虽然和 vue-property-decorator 的装饰器方式不同,但 Composition API 提供了一种更灵活和直观的方式来开发 Vue 组件。 总结来说,vue-property-decorator 是用于 Vue 2.x 版本的装饰器库,而 Vue 3.x 引入了新的 Composition API,取代了 vue-property-decorator,提供了更好的开发体验和更多的功能。所以在 Vue 3.x 中使用 vue-property-decorator 是不可行的,我们需要使用 Composition API 来替代。 ### 回答2: vue-property-decorator是一个用于在Vue组件中使用装饰器语法的库。它使我们能够更加简洁和优雅地编写Vue组件,同时提供了一些强大的功能和特性。 首先,vue-property-decorator允许我们使用装饰器来定义组件的属性,方法和计算属性。通过使用装饰器,我们可以将组件的相关代码集中在一起,使代码更加易读和易维护。例如,我们可以使用@Prop装饰器来定义组件的属性,并指定其类型和默认值。我们还可以使用@Watch装饰器来监听属性或计算属性的变化。 其次,vue-property-decorator提供了一些方便的装饰器来简化对组件生命周期钩子的使用。我们可以使用@Emit装饰器来触发自定义事件,使用@Provide装饰器来提供数据,使用@Inject装饰器来注入数据等。这些装饰器使我们能够更加方便地在组件之间进行通信和共享数据。 此外,vue-property-decorator还提供了一些装饰器来简化对Vue指令和插件的使用。通过使用@Directive装饰器,我们可以定义自定义指令并将其应用到组件中,而无需手动注册和使用指令。类似地,使用@Plugin装饰器,我们可以将第三方插件集成到组件中,从而增强组件的功能。 总而言之,vue-property-decorator是一个强大而灵活的库,它使我们能够更加方便地使用装饰器语法编写Vue组件。它提供了一些强大的功能和特性,使我们的代码更加简洁和易读。对于使用Vue 3的开发者来说,vue-property-decorator无疑是一个很好的选择。 ### 回答3: vue-property-decorator是一个用于Vue.js框架的装饰器库,它能够简化开发者在使用类风格的语法时对Vue组件属性的管理和操作。 在Vue.js 3版本中,vue-property-decorator已经进行了更新和迁移,与Vue.js 2版本的使用稍有区别。在Vue.js 3中,可以使用新的@Options装饰器以替代之前的@Component装饰器,同时也可以继续使用@property装饰器来声明和管理组件的属性。 @Options装饰器可以用于修饰一个Vue组件类,它接受一个配置对象作为参数,用来定义组件的选项和行为。例如: ``` import { Options, Vue } from 'vue-property-decorator'; @Options({ props: { message: { type: String, required: true } } }) export default class MyComponent extends Vue { // 组件的其他逻辑... } ``` 上述代码中,使用@Options装饰器修饰了一个Vue组件类,并通过props字段定义了一个名为message的属性,类型为String,且是必需的。 同时,我们仍然可以使用@property装饰器来声明和管理组件的其他属性。例如: ``` import { Options, Vue, property } from 'vue-property-decorator'; @Options({}) export default class MyComponent extends Vue { @property({ type: String }) message: string = ''; // 组件的其他逻辑... } ``` 上述代码中,使用@property装饰器修饰了一个名为message的属性,并指定了它的类型为String。 总的来说,vue-property-decorator能够简化Vue.js 3中使用类风格语法时对组件属性的管理和操作,提供了方便的装饰器来声明和定义组件的属性,并与Vue的选项和行为进行集成。使用它可以使代码更易读、更易维护。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yusirxiaer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值