vue-property-decorator

vue-property-decorator是基于typescript的Vue库,它为Vue组件提供装饰器,简化了数据、生命周期、方法、组件和计算属性的声明。通过使用@Component、@Watch、@Emit等装饰器,开发者可以更优雅地编写Vue应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

是依赖于ts的一个装饰库,用来简化书写

npm

vue-property-decorator是vue-class-component的进一步封装,提供了

 写法

<script lang='ts'>
import {Component, Vue} from vue-property-decorator;
@Component
export default class App extends Vue {

};
</script>

template和css写法不变,只是在script上加上lang='ts':script声明当前语言是ts

@Component:注明此类为一个vue组件 export default class Test extends Vue:当前组件类继承vue

data中定义的数据改为在对象中书写

export default class App extends Vue {
  private msg1 : string = '123';
  private msg2 : number = 1;
}

生命周期 

export default class App extends Vue {
  private created(){
    this.init();
  }
}

方法 

export default class App extends Vue {
  private init(){
    console.log('init');
  }
}

组件 

export default class App extends Vue {
  private init(){
    console.log('init');
  }
}

watch 

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

export default class App extends Vue {
  @Watch('child')
  onChangeChildValue(newValue: string, oldValue: string){
    ......todo
  }

  @Watch('parent', {immediate: true, deep: false})
  private onChangeParentValue(newValue: string, oldValue: string){
    ......todo
  }
} 

计算属性

对于Vue中的计算属性,我们只需要将该计算属性名定义为一个函数,,在函数前加上get关键字即可,原本Vue中的computed里的每个计算属性都变成了在前缀添加get的函数。

public get computedMsg(){
      return '这里是计算属性' + this.message;
}
public set computedMsg(message: string){
}

@Emit

定义emit事件,参数字符串表示分发的事件名,如果没有,则使用方法名作为分发事件名,会自动转连字符写法:

  1. @Emit()不传参数,那么它触发的事件名就是它所修饰的函数名.
  2. @Emit(name: string),里面传递一个字符串,该字符串为要触发的事件名.

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)
    },
    promise() {
      const promise = new Promise(resolve => {
        setTimeout(() => {
          resolve(20)
        }, 0)
      })

      promise.then(value => {
        this.$emit('promise', value)
      })
    }
  }
}

 TS

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()
  promise() {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve(20)
      }, 0)
    })
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值