当前位置: 移动技术网 > IT编程>开发语言>JavaScript > vue-property-decorator使用指南

vue-property-decorator使用指南

2019年07月19日  | 移动技术网IT编程  | 我要评论

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

1、安装npm i -s vue-property-decorator

2、@component

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

3、@prop 父子组件之间值的传递

@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
  @prop([string,number]) propb:string|number;
  @prop({
    type: string,// type: [string , number]
    default: 'default value', // 一般为string或number
    //如果是对象或数组的话。默认值从一个工厂函数中返回
    // defatult: () => {
      // return ['a','b']
    // }
    required: true,
     validator: (value) => { return [ 'inprocess', 'settled' ].indexof(value) !== -1 } }) propc:string;
}

注意title参数中的感叹号。如果需要设置为true或者有默认道具,我只使用它。如果没有,那么你应该使用| undefined。

“明确的赋值断言是一个特性,允许在实例属性和变量声明之后放置!以向typescript传递一个变量确实被分配用于所有意图和目的,即使typescript的分析无法检测到它。”

@componentexport default class mycomponent extends vue {
  @prop({ required: true }) title!: string
  @prop() optionalitem: string|undefined
}

4、@emit

@emit(event?: string) decorator

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

5、@watch

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

 

 

 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网