Issue
I've been working with Vue for a bit now but have started moving to implementations with Typescript. I'm running into an issue where I'm not able to access the child's methods via the refs on the parent.
Parent Code:
<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>
Child Code:
<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>
The issue I'm seeing is that in the parent when I reference the child with const child = this.$refs.child as RefTest;
I'm seeing the error: 'RefTest' refers to a value, but is being used as a type here.
. In addition, the child.pingMe();
is reporting: Property 'pingMe' does not exist on type 'Vue'.
I've tried various work arounds found here: https://github.com/vuejs/vue/issues/8406 primarily around the inferface definitions and the Vue.extend<>
call.
I appreciate any help with helping me continue to wrap my brain around the differences with using Typescript.
Solution
Ok. Did some more experimenting and I'm not sure this is the 'right' solution or most elegant but the code works and the compiler isn't complaining. Ultimately I created an interface type that contains the method I'm trying to reach. In the parent I now cast the $ref as that interface type and all appears to be well. Please let me know if there is a better more elegant way of doing this (or if this is the 'best' way) Please see full code below.
Interface (types/refInterface.ts):
import Vue from "vue";
export interface RefInterface extends Vue {
pingMe(): void;
}
Parent:
<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>
The 'child' code did not change for this to work so did not re-paste it.
Answered By - djneely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.