Home > Mobile >  Vue.js with TypeScript - getting the type of the ref child component
Vue.js with TypeScript - getting the type of the ref child component

Time:07-22

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.

CodePudding user response:

Your code looks fine and it should work as child component ref holds 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.

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <child ref="childCom"></child>
</div>

Vue.component('child', {
    methods: {
    testFunction() {
        console.log('test function call')
    }
  }
});

var app = new Vue({
  el: '#app',
  mounted() {
    (this.$refs.childCom as Child).testFunction();
  }
});

Demo Link : https://jsfiddle.net/w6bjso78/

CodePudding user response:

So far this is the solution I found:

(this.$refs.childRef as Child & { testFunction:() => void }).testFunction();

It works although I don't know if this is a clean apporach. It updates the Child type with a void method testFunction.

  • Related