My parent component has a child component called with reference passed to it:
<child
ref="childRef"
/>
Now from the parent component I want to run the function which is inside child component like this:
mounted() {
(this.$refs.childRef as any).testFunction();
}
Of course it's working fine with any type, but how do I set the correct type to run this function?
If I use the type of the component itself:
(this.$refs.childRef as Child).testFunction();
it still says that property testFunction does not exist on type 'Vue'.
I use the 2 version of Vue.js.
My child component:
@Component({})
export default class Child extends Mixins(CustomMixin) {
testFunction() {
console.log('test');
}
}
EDIT: Also I found this solution to run the function:
(this.$refs.childRef as Child & { testFunction:() => void }).testFunction();
It updates the Child type with the method testFunction() and it actually works. Although I don't know if this is a good approach.
Your code looks fine and it should work as child component
refholds the instance of Child component only. Here is the code snippet. Please have a look and crosscheck with your code to find out the root cause.Demo Link : https://jsfiddle.net/w6bjso78/