vue-property-decorator 装饰器详解

简述

近期对于vue-property-decorator使用还是比较频繁,所以梳理一下其实内容不多

本文的方式是翻译一下 官方文档 再配以自己的理解笔者自己的话会以引入的形式体现以区分原文

这就是我说的话

现在让我们开始

这个库完全依赖于vue-class-component,所以请在使用这个库之前阅读其自述文件。

就是说@Component这个装饰器的文档看vue-class-component的,因为它就是引入了他的再抛出来

安装方法

npm i -S vue-property-decorator

使用方法

有几个装饰器和1个函数(Mixin):

  • @Prop
  • @PropSync
  • @Model
  • @ModelSync
  • @Watch
  • @Provide
  • @Inject
  • @ProvideReactive
  • @InjectReactive
  • @Emit
  • @Ref
  • @VModel
  • @Component (provided by vue-class-component)
  • Mixins (the helper function named mixins provided by vue-class-component)

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

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

@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
}

等于

export default {
  props: {
    propA: {
      type: Number,
    },
    propB: {
      default: 'default value',
    },
    propC: {
      type: [String, Boolean],
    },
  },
}

这一段还是很简单明了的,就是把prop换成了@Prop然后把属性啥的都传入
不过有一点,我在实际应用中并没有用到传入类型的场景,可能因为ts的类型检查,所以传入不传入都差别不大个人感觉。还有就是记得加类型断言如果不为空的话

  1. 如果要从其类型定义中设置每个道具值的类型属性,则可以使用 reflect-metadata
    设置 emitDecoratorMetadata 为 true
  2. 只需要在导入 vue-property-decorator之前导入一次reflect-metadata即可
import 'reflect-metadata'
import { Vue, Component, Prop } from 'vue-property-decorator'

@Component
export default class MyComponent extends Vue {
  @Prop() age!: number
}

个人觉得意义不大,按需取用吧

每个属性的默认值都需要定义的和上面所示的示例代码一样。
不支持定义每个默认属性,如@Prop() prop = 'default value'

意思就是默认值得写在@Prop({default :''xxx}) private xxx!:number这样
在实际应用中笔者用的最多的就是@Prop({default}) @Prop({require})并且这两个属性是互斥的,没有同时存在的意义

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

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

@Component
export default class YourComponent extends Vue {
  @PropSync('name', { type: String }) syncedName!: string
}

等于

export default {
  props: {
    name: {
      type: String,
    },
  },
  computed: {
    syncedName: {
      get() {
        return this.name
      },
      set(value) {
        this.$emit('update:name', value)
      },
    },
  },
}

@PropSync的工作原理就像@Prop一样,除了它将propName作为装饰器的参数,而且还在背后创建了一个计算属性的get和set。通过这种方式,您可以使用这个传入的prop,就像它是一个常规数据属性一样,同时使它可在父组件中附加.sync修饰符。

一个很好用的属性,在做弹窗啥的时候,就很方便,只要在父级传入的该属性的时候加上.sync就可以实现父子级的双向绑定,代码简洁不少还是像@Prop一样我基本不传类型

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

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

@Component
export default class YourComponent extends Vue {
  @Model('change', { type: Boolean }) readonly checked!: boolean
}

等于

export default {
  model: {
    prop: 'checked',
    event: 'change',
  },
  props: {
    checked: {
      type: Boolean,
    },
  },
}

@Model属性还可以通过reflect-metadata从其类型定义中设置type。

真没用过,个人觉得很鸡肋,随便写点啥也不能用啊,了解一下吧 ,如果不了解双向绑定原理啥的请自行查阅文档

@ModelSync(propName: string, event?: string, options: (PropOptions | Constructor[] | Constructor) = {}) decorator

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

@Component
export default class YourComponent 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)
      },
    },
  },
}

@ModelSync 属性还可以通过reflect-metadata从其类型定义中设置type。

这个属性也是挺好用的可以实现父组件在外面v-model 而不是.sync的需求,还有就是这两个值其实都可以随便传,因为父级使用v-model实现的话根本不认属性是什么,当然如果父级不使用v-model而是手动绑定啥的就有用了

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

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) {}
}

等于

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(key?: string | symbol) / @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,
    }
  },
})

这个代码已经一目了然了,provide inject用的比较少,如果不知道这两个属性是干嘛的,建议看看vue官方文档,我只有在做插件的时候用过一次两次

@ProvideReactive(key?: string | symbol) / @InjectReactive(options?: { from?: InjectKey, default?: any } | InjectKey) decorator

这些装饰器是@Provide和@Inject的响应式版本。如果父组件修改了提供的值,则子组件可以捕获此修改。

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(event?: string) decorator

由@Emit $emit的函数发出返回值,后面是原始参数。如果返回值是一个Promise,则在resolved之前运行它。

如果事件没有通过事件参数提供事件的名称,则改为使用函数名称。在这种情况下,函数的名称会被转换成xxx-xxx式的

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

@Component
export default class YourComponent 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)
      })
    },
  },
}

一开始一直觉得鸡肋,但是使用过之后才明白了这个设计的意义,其实是为了在使用$emit的时候能够得到类型保护,比如你执行了很大一段,然后执行 一个 带有$Emit()的函数它其实就是替代了$emit,并且使你获得了类型保护,所以用处还是很大的,不过关于eventBus的 $emit可以设计一个接口来实现类型保护

@Ref(refKey?: string) decorator

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

import AnotherComponent from '@/path/to/another-component.vue'

@Component
export default class YourComponent 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
      }
    }
  }
}

最后一个用处很大的装饰器,可以解决使用 refs使得不到类型提示的痛苦

@VModel(propsArgs?: PropOptions) decorator

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

@Component
export default class YourComponent 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)
      },
    },
  },
}

确实没用过,很鸡肋,专门为 输入类组件写的

结束
本文译自:https://github.com/kaorun343/vue-property-decorator

以上均为个人经验,如有错误,请指正

### 回答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的选项和行为进行集成。使用它可以使代码更易读、更易维护。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值