Vue.js : Call a Method from another Component

Viewed 233

this is my HTML from Component1

 <component2></component2>

this is my <script> from Component1

export default {
 
  methods: {
    fetchData()
    {
    ...
    }
 }
}

and i wanna call the method fetchData() in Component2

my <script> from component2

 export default {
     ...
    }

i tried: this.$root.$refs.c1= this; ... this.$root.$refs.c1.fetchData()

i tried to set an event

nothing worked

2 Answers

You could call emit on Component2 and call fetchData when Component1 receives it:

<component2 @fetch="fetchData()"></component2>

And on Component2, you need to emit fetch at somepoint. For example:

export default {
    created() {
        this.$emit('fetch')
    }
}

Template in Component2 should equal:

 <component2 ref="childComp"></component2>

Then your fetchData method in Component1 could look like:

export default {
  methods: {
    fetchData() {
      return this.$refs.childComp.fetchData();
    }
  }
}
Related