如何访问打字稿中的 Vue 计算属性?

时间:2021-06-28 00:27:49

标签: typescript vue.js

我试图在另一个或内部方法中使用计算属性并得到错误: Property 'comments' does not exist on type 'Vue'

import { Component, Vue } from 'vue-property-decorator'
@Component({
  computed: {
    comments(): Comment[] {
      return this.$store.getters['comments/getComments'];
    },
    hasComments(): boolean {
      return (0 !== this.comments.length); // Property 'comments' does not exist on type 'Vue'
    }
  }
})
export default class Test extends Vue {
  public get commentsCount(): number {
    return this.comments.length; // Property 'comments' does not exist on type 'Vue'
  }
}

我用 (this as any).comments 替换它并且它没有错误地工作,但是使用 typescript 并忽略 any 的类型检查有什么意义。

2 个答案:

答案 0 :(得分:1)

变量 comments 存在于 Javascript 运行时中,这里的问题是它没有在 Typescript 中定义,您可以通过声明变量,然后在变量定义之后使用 ! 运算符,这是 non-null 断言操作,它告诉 Typescript 你的变量正在其他地方初始化(在这种情况下由 装饰器)

代码段

  public comments!: TYPE_OF_COMMENTS;

完整代码


import { Component, Vue } from 'vue-property-decorator'
@Component({
  computed: {
    comments(): Comment[] {
      return this.$store.getters['comments/getComments'];
    },
    hasComments(this: Test): boolean {
      return (0 !== this.comments.length);
    }
  }
})
export default class Test extends Vue {
  public comments!: TYPE_OF_COMMENTS;

  public get commentsCount(): number {
    return this.comments.length; // Property 'comments' does not exist on type 'Vue'
  }
}

更新:

对于 hasComments 的情况,您可以更改为 this 实例提供的值,因为您可以指向您的实际组件而不是默认的 Vue 实例。

你可以这样实现:

    hasComments(this: Test): boolean { 
      return (0 !== this.comments.length);
    }

如您所见,this 实例具有组件 (Test) 的类型定义。

答案 1 :(得分:0)

我过去在 Vue 2 中遇到过类似的错误(Vue 3 更好,尤其是使用组合 API)。从来没有一个特定的修复,但一个常见的修复是确保我的计算属性具有准确的返回类型,并且有一个用于我的计算属性的默认值。

我会将此添加为评论,但我没有足够的代表,但是您可以尝试在您的 comments() 返回中提供一个默认值吗?你已经输入它返回一个 Comment[] 但 Typescript/Vue 可能不知道你正在获取的 store 值正是那个(或者它是否存在)。