In my parent component, I have a child component named with a reference passed to it:
<child
ref="childRef"
/>
When trying to execute a function inside the child component from the parent component, I face some challenges:
mounted() {
(this.$refs.childRef as any).testFunction();
}
The above code works without specifying a type, but how can I set the correct type for running this function?
If I try to specify the type of the child component like this:
(this.$refs.childRef as Child).testFunction();
I still get an error saying that property testFunction
does not exist on type 'Vue'.
I am using Vue.js version 2.
This is the code for my child component:
@Component({})
export default class Child extends Mixins(CustomMixin) {
testFunction() {
console.log('test');
}
}
Update: I also came across this solution to call the function successfully:
(this.$refs.childRef as Child & { testFunction:() => void }).testFunction();
This updates the Child type with the method testFunction()
and it works. However, I am unsure if this is the best approach.