如何键入使用Vue.extend创建的Vue组件?

时间:2020-09-06 15:16:13

标签: javascript typescript vue.js

使用Vue和TypeScript,我已经使用 Vue.extend 创建了两个组件。我现在想从另一个通过 this。$ refs 访问其中一个,但是如果我未指定其类型,则无法通过IDE自动完成功能访问其任何方法:

// ChildComponent.vue

export default Vue.extend({
  name: 'ChildComponent',
  methods: {
    test(): void { ... }
  }
}

// ParentComponent.vue

<template>
  <ChildComponent ref="child_ref" />
</template>

export default Vue.extend({
  name: 'ParentComponent',
  components: { ChildComponent }
  computed: {
    child(): InstanceType<typeof ChildComponent> { // This won't work 
      return this.$refs.child_ref as InstanceType<typeof ChildComponent>;
    }
  },
  methods: {
    triggerChildTest(): void {  
      this.child.test(); // IDE warning: Property 'test' does not exist on type 'CombinedVueInstance'.
    }
  }
}

有什么方法可以继续使用 Vue.extend ,从而允许我从组件中访问数据和方法?我可以以某种方式在生成的组件上实现接口吗? 与将所有内容迁移到使用Vue组件类相比,我宁愿保留我的代码库使用这种方法。

0 个答案:

没有答案