• 【Vue实践】装饰器(vue-property-decorator 和 vux-class)的使用


    目前在用vue开发的项目中,都会配合使用TypeScript进行一些约束。为了提高开发效率,往往会使用装饰器来简化我们的代码。

    本文主要介绍装饰器vue-property-decorator vux-class的使用。

    1. 安装

    npm i -S vue-property-decorator
    npm i -S vuex-class
    
    • 1
    • 2

    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{
       
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    相当于:

    export default{
      name: 'MyComponent',
      components:{
        componentA,
        componentB,
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    @Prop

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

    表示:@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
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    相当于:

    export default {
      name: 'MyComponent',
      props: {
        propA: {
          type: Number,
        },
        propB: {
          default: 'default value',
        },
        propC: {
          type: [String, Boolean],
        },
      },
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    @PropSync

    @PropSync(propName: string, options: (PropOptions | Constructor[] | Constructor) = {}) decorator
    
    • 1
    • propName 表示父组件传递过来的属性名
    • 父组件要结合.sync来使用

    例如:

    // child.vue
    import { Vue, Component, PropSync } from 'vue-property-decorator'
     
    @Component
    export default class MyComponent extends Vue {
      @PropSync('name', { type: String }) syncedName!: string
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    
    <template>
      <div>
        <MyComponent  :name.sync="name" />
      div>
    template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    相当于:

    export default {
      name: 'MyComponent',
      props: {
        name: {
          type: String,
        },
      },
      computed: {
        syncedName: {
          get() {
            return this.name
          },
          set(value) {
            this.$emit('update:name', value)
          },
        },
      },
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    @PropSync的工作原理与@Prop类似,除了接受propName作为装饰器的参数之外,它还在幕后创建了一个计算的getter和setter。通过这种方式,您可以像使用常规数据属性一样使用该属性,同时像在父组件中添加.sync修饰符一样简单。

    @Model

    @Model装饰器允许我们在一个组件上自定义v-model。

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

    例如:

    import { Vue, Component, Model } from 'vue-property-decorator'
     
    @Component
    export default class MyComponent extends Vue {
      @Model('change', { type: Boolean }) readonly checked!: boolean
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    相当于:

    export default {
      model: {
        prop: 'checked',
        event: 'change',
      },
      props: {
        checked: {
          type: Boolean,
        },
      },
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    @ModelSync

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

    例如:

    import { Vue, Component, ModelSync } from 'vue-property-decorator'
     
    @Component
    export default class MyComponent extends Vue {
      @ModelSync('checked', 'change', { type: Boolean }) readonly checkedValue!: boolean
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    相当于:

    export default {
      model: {
        prop: 'checked',
        event: 'change',
      },
      props: {
        checked: {
          type: Boolean,
        },
      },
      computed: {
        checkedValue: {
          get() {
            return this.checked
          },
          set(value) {
            this.$emit('change', value)
          },
        },
      },
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    @Watch

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

    例如:

    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) {}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    相当于:

    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) {},
      },
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    @Provide | @Inject

    @Provide(key?: string | symbol) decorator
    @Inject(options?: { from?: InjectKey, default?: any } | InjectKey) decorator
    
    • 1
    • 2

    例如:

    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'
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    相当于:

    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,
        }
      },
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    @ProvideReactive | @InjectReactive

    它们是@provider@Inject的响应式版本。如果父组件修改了提供的值,那么子组件可以捕捉到这种修改。

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

    例如:

    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
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    @Emit

    @Emit(event?: string) decorator
    
    • 1

    例如:

    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)
        })
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    相当于:

    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)
          })
        },
      },
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    @Ref

    Ref(refKey?: string) decorator
    
    • 1

    例如:

    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
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    相当于:

    export default {
      computed() {
        anotherComponent: {
          cache: false,
          get() {
            return this.$refs.anotherComponent as AnotherComponent
          }
        },
        button: {
          cache: false,
          get() {
            return this.$refs.aButton as HTMLButtonElement
          }
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    @VModel

    @VModel(propsArgs?: PropOptions) decorator
    
    • 1

    例如:

    import { Vue, Component, VModel } from 'vue-property-decorator'
     
    @Component
    export default class MyComponent extends Vue {
      @VModel({ type: String }) name!: string
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    相当于:

    export default {
      props: {
        value: {
          type: String,
        },
      },
      computed: {
        name: {
          get() {
            return this.value
          },
          set(value) {
            this.$emit('input', value)
          },
        },
      },
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    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/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']
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
  • 相关阅读:
    GFS分布式文件系统&实验
    二.镜头知识之镜头总长,法兰距,安装接口
    ceph分布式存储
    算法 只出现一次的两个数字-(哈希+异或)
    【面试题】c++实现简易单链表
    YOLOv5源码中的参数超详细解析(1)— 项目目录结构及文件(包括源码+网络结构图)
    Flyway 入门教程
    华为云云服务器云耀L实例评测 | 从零到一:华为云云耀云服务器L实例上手体验
    depends工具查看exe和dll依赖关系
    在WSL中使用code . 启动vscode失败 解决
  • 原文地址:https://blog.csdn.net/baidu_36511315/article/details/126328767