[Vuejs]-How to build a bridge of events between different components in Vue?

0👍

The best practice is to use Vuex State manager with computed methods (getters) and watchers

I have made a working example for you on jsfiddle.
https://jsfiddle.net/n4e_m16/wujafg5e/4/

For more info on how vuex works please go to Here

Please let me know if you need more help 🙂

const store = new Vuex.Store({
  state: {
    mainMidLeftState: false,
  },

  getters: {
    mainMidLeftState: state => state.mainMidLeftState,
  },

  mutations: {
    toggleMainMidLeft: (state, payload) => {
      state.mainMidLeftState = !state.mainMidLeftState
    },
  },
})


Vue.component('main-mid-left', {
  data() {
    return {

    }
  },
  computed: {
    mainMidLeftState() {
      return this.$store.state.mainMidLeftState
    },
  },
  methods: {

    toggleMainMidLeft() {
      this.$store.commit('toggleMainMidLeft')
      //  alert(this.mainMidLeftState)
    },
  }
})

Vue.component('slide-left-top', {
  data() {
    return {

    }
  },
  computed: {
    mainMidLeftState() {
      return this.$store.state.mainMidLeftState
    },
  },
  watch: {
    mainMidLeftState: function(val) {
      alert("YES, computed property changed and alert have been triggered by watcher in slide top left component")
    }
  },
  methods: {

  }
})

const app = new Vue({
  el: '#app',
  store,
})
div {
  color: black;
}
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js"></script>

<div id="app">

  <!-- inlining the template to make things easier to read - all of below is held on the component not the root -->
  <main-mid-left inline-template>
    <div>
      <h4>
        main mid left
      </h4>
      <button v-on:click="toggleMainMidLeft()">toggle Main Mid Left State</button>

      <div v-show="mainMidLeftState == true">State is true</div>
      <div v-show="mainMidLeftState == false">State is false</div>
    </div>


  </main-mid-left>

  <slide-left-top inline-template>
    <div>

      <h4>
        slide left top
      </h4>
      <div v-show="mainMidLeftState == true">State is true</div>
      <div v-show="mainMidLeftState == false">State is false</div>
    </div>
  </slide-left-top>
</div>

0👍

If you don’t want to use vuex, you can create a new Vue instance as an event bus (I believe this is mentioned somewhere in the Vue tutorial):

const EventBus = new Vue()

Import EventBus to where you need it and you can send an event by:

EventBus.$emit('event-name', data)

And add the following script in created() of your receiver component:

EventBus.$on('event-name', ($event) => {
        // Do something
    })

I hope this helps |´・ω・)ノ

Leave a comment