Search code examples
vue.jsvuejs3vue-options-api

How to access method from the child component in parent in Vue.js


I want to access the method in parent component and the method is present in child component. I tried using mixins. But the function is returning null instead of value. If i try to emit the object and that is working fine in parent component. How can I access the child method in parent other in vue3 Options API

Parent.vue

export default defineComponent({
  name: 'App',
  components: {
    HelloWorld
  },
  mixins: [HelloWorld],
  methods: {
    fetchval(){
      let x = this.getVal();
      console.log(x);
    }
  }
});
</script>

Child.vue

export default defineComponent({
  name: 'HelloWorld',
  dat(){
    let val!: string;
    return{
      val,
    }
  },
  computed: {
    value: {
      get() {
        return this.val as string;
      },
      set(newval) {
        val = newval;
      }
    }
  },
  methods: {
   getVal(){
     return this.value as string;
   }
 }
});
</script>

Solution

  • Probably better to rethink the control flow, so that it have a clear separation of concern

    • A parent should not directly access child's method. If the method should be invoked via a button click, then the child can process the click and emit the event back to parent callabck handler. For details, check this

    • You may also check out state management, it can achieve what you want. Doc Link

    Having said that, declaring a component in the parent and also include that component in parent's mixin doesn't seem common, and may not be a good practice.

    Just a quick answer, there might be more way to achieve what you desire.