vue中使用vue-class-component写TS

vue上所有生命周期中的钩子方法里(如created,mounted,updated)使用this,this指向调用它的vue实例 (new Vue),this的指向会影响ts的类型推断,为了更好地用class的模式来写vue组件。
vue-class-component 带来了很多遍历 官网
1.methods,钩子都可以直接写作class的方法
2.computed属性可以直接通过get来获得
3.初始化data可以声明为class的属性
4.其他的都可以放到Component装饰器里
vue-property-decorator深度依赖了vue-class-component,拓展出了更多操作符:@Prop、@Emit、@Inject、@Model、@Provide、@Watch;等可以写在class里面

创建组件的方式

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

@Component 
export default class Test extends Vue {

}

data对象(可以直接声明为class的属性)

export default class Test extends Vue {
  private name: string;
}

prop声明(两种方式)

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

@Component({
    mixins: [],
    // props传值(方法一)
    props: {
        firstName: String,
        lastName: String
    },
    // 注册组件
    components: {
        'component-a': ComponentA
    }
})
export default class Test extends Vue {
// props传值(方法二)
@Prop({ default: "test" }) private label!: string;
}

method方法(直接写作class的方法)

public func(): void {
  console.log(this.name)
}

watch 属性监听

// immediate 立即触发
@Watch("$route", { immediate: true })
private onRouteChange(route: Route) {
  const query = route.query as Dictionary<string>; // ts类型断言
  if (query) {
  this.redirect = query.redirect;
  }
}
  • @Watch(path: string, options: WatchOptions = {})
    options 包含两个属性 immediate?:boolean 侦听开始之后是否立即调用该回调函数 / deep?:boolean 被侦听的对象的属性被改变时,是否调用该回调函数

  • @Watch('arr', { immediate: true, deep: true }) onArrChanged(newValue: number[], oldValue: number[]) {}

computed 计算属性(computed属性可以直接通过get来获得)

public get allname() {
  return 'computed ' + this.name;
}
// allname 是计算后的值,name 是被监听的值

生命周期函数

public created(): void {
  console.log('created');
}

public mounted():void{
  console.log('mounted')
}

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
  }
}
原文地址:https://www.cnblogs.com/whkl-m/p/15012419.html