[Vuejs]-Vue: How to call a function within a sibling component?

2👍

You can use refs like so:

<parent>
 <modal @triggerFunc="triggerFunc"/>
 <cart ref="$cartRef"/>
</parent>

...
triggerFunc(){
   this.$refs.$cartRef.functionIwantToTrigger()
}

1👍

0👍

You can use Custom Events for this using the root Vue instance of the current component tree.

In Modal.vue:

Where you are getting a response back from a call, simply emit a custom event like:

this.$root.$emit('onupdate', data);

In Cart.vue:

Simply listen to this root emitted event like

var vm = new Vue({
  data: {},
  mounted() {
    this.$root.$on('onupdate', data => {
      // trigger a function within Cart.vue
      this.myFunction(data)
    });
  }
  methods: {
    myFunction: function(data) {
      console.log(data);
    }
  }
})

Leave a comment