簡體   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