首页 > 解决方案 > TypeScript 抱怨使用 vue-property-decorator 定义的现有 Vue 组件属性

问题描述

我有一个 Vue 组件,它有一个使用装饰器定义的属性:

import { Component, Vue } from "vue-property-decorator"
@Component({
             props: {
               myId: String,
             },
           })
class TestProp extends Vue {
  myFunction(obj: any) {
    return obj[this.myId] // here tslint complains: "Property 'myId' does not exist on type 'TestProp'."
  }
}

我可以通过转换为来避免类型this错误any

  myFunction(obj: any) {
    return obj[(this as any).myId]
  }

但这与其说是解决方案,不如说是一种解决方法。

@Component我猜编译器不知道装饰器定义的属性?

有任何想法吗?

标签: javascripttypescriptvue.jstslint

解决方案


我推荐你使用这个库:https ://github.com/kaorun343/vue-property-decorator

有了这个,你可以在你的组件类中声明你的道具。

例如:

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

@Component
class TestProp extends Vue {
  @Prop(String) myId: string!
}

推荐阅读