【问题标题】:how to declare methods in child vue component?如何在子 vue 组件中声明方法?
【发布时间】:2021-09-08 13:27:51
【问题描述】:

child.vue:

<script lang="ts">
import { Vue } from 'vue-property-decorator'

@Component
export default class Child extends Vue {
  public func(): void {
    //
  }
}
</script>

parent.vue:

<template>
  <child ref="child" />
</template>

<script lang="ts">
  import { Vue } from 'vue-property-decorator'
  import Child from './child.vue'

  export default Parent extends Vue {
    public create (): void {
    (this.$refs.child as typeof Child).func()
  }
}

TSLint 错误:

Property 'func' does not exist on type 'Component<DefaultData<never>, DefaultMethods<never>, DefaultComputed, DefaultProps>'.

如何让 'typeof Child' 被检测为 Class Child?我知道创建一个额外的接口然后导入它可以解决这个问题,但是还有其他方法吗?

【问题讨论】:

    标签: javascript typescript vue.js ecmascript-6


    【解决方案1】:

    首先:您忘记了父组件上的 @Component 装饰器。它不会正确输入。

    第二个(可选):您可以使用 @Ref 装饰器来保留您的 ref 的类型化引用。

    第三:你不需要typeof关键字。

    @Ref('child')
    readonly childComponent: Child
    
    created () {
       // Correctly typed
       this.childComponent.func()
    }
    

    【讨论】:

    • 我刚刚意识到这是来自 VSCode 中 Vetur 验证服务而不是 TSLint 的错误消息,禁用 ts 的 Vetur 验证,错误消失,无论 refs.child 被声明为 Child 或 'typeof Child' 还是 sth否则。
    • Vetur 只是显示来自 typescript 编译器的错误消息,因为 TS 无法读取 .vue 文件。如果您尝试实际编译,您将再次看到该错误。
    猜你喜欢
    • 1970-01-01
    • 2017-09-02
    • 2021-09-24
    • 2020-12-24
    • 2020-08-13
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-05
    相关资源
    最近更新 更多