【问题标题】:TypeScript complains about existing Vue component property defined with vue-property-decoratorTypeScript 抱怨使用 vue-property-decorator 定义的现有 Vue 组件属性
【发布时间】:2019-12-05 00:56:45
【问题描述】:

我有一个 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 装饰器定义的属性?

有什么想法吗?

【问题讨论】:

  • 请分享完整的错误详情

标签: javascript typescript vue.js tslint


【解决方案1】:

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

这样你就可以在你的组件类中声明你的道具了。

例如:

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

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

【讨论】:

  • 我添加了另一个答案,但这是我一直在寻找但没有找到的。 Vue需要转换成这种方式而不是单个装饰器
  • 这种声明属性的方式非常好,谢谢!
【解决方案2】:

TypeScript example 声明您必须自己在组件中记录它们。

从那个页面

  // additional declaration is needed
  // when you declare some properties in `Component` decorator
import { Component, Vue } from "vue-property-decorator"
@Component({
  props: {
    myId: String,
  },
})
class TestProp extends Vue {

  myId: string;

  myFunction(obj: any) {
    return obj[this.myId] // here tslint complains: "Property 'myId' does not exist on type 'TestProp'."
  }
}

【讨论】:

  • 感谢您指出这个例子。但是,在示例中,propMessage 没有在类中再次声明...
  • 那个例子是错误的,你用它不会编译的
猜你喜欢
  • 1970-01-01
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 2021-10-11
  • 2019-12-17
  • 2020-09-15
  • 2020-03-10
  • 2018-09-14
相关资源
最近更新 更多