Vue Typescript子组件方法

时间:2020-04-29 16:37:06

标签: typescript vue.js vue-component

我已经与Vue合作了一段时间,但是已经开始转向使用Typescript的实现。我遇到了一个问题,即我无法通过父项上的引用访问子项的方法。

父代码:

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

<script lang="ts">
import Vue from "vue";
import RefTest from "./RefTest.vue";

export default Vue.extend({
  name: "RefParent",
  components: {
    RefTest
  },
  data: () => ({}),
  methods: {},
  mounted() {
    const child = this.$refs.child as RefTest;
    child.pingMe();
  }
});
</script>

<style scoped></style>

子代码:

<template>
  <div>REF TEST...</div>
</template>

<script lang="ts">
import Vue from "vue";

export default Vue.extend({
  name: "RefTest",
  data: () => ({}),
  methods: {
    pingMe() {
      console.log("refTest pingMe");
    }
  }
});
</script>

<style scoped></style>

我看到的问题是,当我用const child = this.$refs.child as RefTest;引用孩子时,我在父母中看到错误:'RefTest' refers to a value, but is being used as a type here.。另外,child.pingMe();正在报告:Property 'pingMe' does not exist on type 'Vue'.

我尝试了以下各种解决方法:https://github.com/vuejs/vue/issues/8406主要围绕接口定义和Vue.extend<>调用。

我非常感谢使用Typescript可以帮助我继续围绕差异解决问题。

1 个答案:

答案 0 :(得分:1)

好的。做了更多的实验,我不确定这是“正确”的解决方案还是最优雅的解决方案,但是代码可以正常工作并且编译器没有抱怨。最终,我创建了一个接口类型,其中包含我要尝试的方法。在父级中,我现在将$ ref转换为该接口类型,并且一切看起来都很好。请让我知道是否有更好的更优雅的方法(或者这是“最佳”方法),请参见下面的完整代码。

接口(类型/refInterface.ts):

import Vue from "vue";

export interface RefInterface extends Vue {
  pingMe(): void;
}

父母:

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

<script lang="ts">
import Vue from "vue";
import RefTest from "./RefTest.vue";
import { RefInterface } from "@/types/refInterface";

export default Vue.extend({
  name: "RefParent",
  components: {
    RefTest
  },
  data: () => ({}),
  methods: {},
  mounted() {
    const child = this.$refs.child as RefInterface;
    child.pingMe();
  }
});
</script>

<style scoped></style>

“子代”代码并未更改,因此未重新粘贴。

相关问题