How to update one component from another component in vue.js

You can use this.$root without global variable:

// component A emits an event
export default {
  name: 'A',
  methods: {
    buttonClicked: function () {
      this.$root.$emit('myEvent', 'new message!');
    }
  }

// component B catch your event
export default {
  name: 'B',
  data () {
    return {
        message: 'Old message!'
    }
  },
  mounted: function () { 
    this.$root.$on('myEvent', (text) => { // here you need to use the arrow function
     this.message = text;
    })
  }
}

It is not allowed to communicate to another component directly. You can use a parent component to communicate between the components or some kind of event bus.

var bus = new Vue();

Component A emits an event while component B may catch it and vice versa.

// component A
bus.$emit('cool_event_name', interesting_data)

// component B
bus.$on('cool_event_name', function(interesting_data) {
   console.log(interesting_data)
})

Another solution might be to use $root which can be accessed from all sub-components of a Vue instance. This economizes on the definition a global bus (like above). Note that this method is not recommended as a general approach and acts more as a solution to certain edge cases.

// component A
this.$root.$emit('cool_event_name', interesting_data)

// component B
this.$root.$on('cool_event_name', function(interesting_data) {
   console.log(interesting_data)
})

Tags:

Vue.Js