Home > Software engineering >  Use method from child component in parent with CDN vue.js
Use method from child component in parent with CDN vue.js

Time:11-05

I just switchend from alpine.js to vue.js (cdn) because i experiment with async frunctions. My goal is to call a method from the parent which is defined in a component.

But when i want to call "test()" in my html file i get the error that "Cannot read properties of undefined (reading 'childRef')" All works fine when the method is defined at the "app" -element (parent) but i dont want to clutter this element with different methods.

Thanks in advance for every hint or remarks to my code.

Code Snippet Vue/Javascript

--------------------------------------
const app = Vue.createApp ({
  data() {
    return {
      visible: false,
      openTab: ''
    }
  },
  methods: {
    test() {
      this.$resfs.childRef.getMyDevices();
    }
  }
})
--------------------------------------
app.component('child',{
  data() {
    return {
      myDevices: {},
    }
  },
  methods: {
    async getMyDevices() {
      const response = await foo.getMyDevices();
      const data = await {...response.devices};

      this.myDevices = data;
    }
  },
  template: `<div ref="childRef"></div>`
})

Code Snippet HTML

<div @click="test()>
  <child ref="childRef"></child>
</div>

CodePudding user response:

There is a typo in your question, jus correct the refs spelling

this.$refs.childRef.getMyDevices()

If the above doesn't work then try using

this.$children[0].getMyDevices()

CodePudding user response:

There was a typo in your $refs accessing:

methods: {
    test() {
      this.$refs.childRef.getMyDevices(); // $resfs befores
    }
  }
  • Related