[Vuejs]-Changing state of component data from sibling component Vue.JS 2.0

2πŸ‘

@craig_h is correct, or you can use $refs like:

<parent-element>
    <sibling-a @onClickButton="changeCall"></sibling-a>
    <sibling-b ref="b"></sibling-b>
</parent-element>

In parent methods:

methods: {
    changeCall() {
      this.$refs.b.dataChange = 'changed';
    }
  }

In siblingA:

Vue.component('sibling-a', {
  template: `<div><button @click="clickMe">Click Me</button></div>`,
  methods: {
    clickMe() {
      this.$emit('onClickButton');
    }
  }
});

In siblingB:

Vue.component('sibling-b', {
  template: `<div>{{dataChange}}</div>`,
  data() {
    return {
      dataChange: 'no change'
    }
  }
});
πŸ‘€Kumar_14

0πŸ‘

For that you can simply use a global bus and emit your events on to that:

var bus = new Vue();

Vue.component('comp-a', {
  template: `<div><button @click="emitFoo">Click Me</button></div>`,
  methods: {
    emitFoo() {
      bus.$emit('foo');
    }
  }
});

Vue.component('comp-b', {
  template: `<div>{{msg}}</div>`,
  created() {
    bus.$on('foo', () => {
      this.msg = "Got Foo!";
    })
  },
  data() {
    return {
      msg: 'comp-b'
    }
  }
});

Here’s the JSFiddle: https://jsfiddle.net/6ekomf2c/

If you need to do anything more complicated then you should look at Vuex

πŸ‘€craig_h

Leave a comment