繁体   English   中英

Vue Typescript 子组件方法

[英]Vue Typescript Child Component Methods

我已经使用 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 的差异。

好的。 做了一些更多的实验,我不确定这是“正确”的解决方案还是最优雅的解决方案,但代码有效并且编译器没有抱怨。 最终,我创建了一个接口类型,其中包含我想要达到的方法。 在父级中,我现在将 $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>

'child' 代码没有改变,所以没有重新粘贴它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM