Search code examples
vue.jsvue-componentvue-cli-3

is it correct global component communication in vue?


i make modal popup components myPopup.vue for global.

and import that in App.vue and main.js i use this for global, define some object Vue.prototype

make about popup method in Vue.prototype like, "show" or "hide", any other.

but i think this is maybe anti pattern.. i want to find more best practice.

in App.vue

<div id="app>
  <my-popup-component></my-popup-conponent>
  <content></content>
</div>

main.js

...
Vue.prototype.$bus = new Vue(); // global event bus
Vue.prototype.$popup = {
  show(params) {
    Vue.prototype.$bus.$emit('showPopup', params);
  },
  hide() {
    Vue.prototype.$bus.$emit('hidePopup');
  }
}

Vue.component('my-popup-component', { ... });
...

myPopup.vue

....
export default {
...

  created() {
    this.$bus.$on('showPopup', this.myShow);
    this.$bus.$on('hidePopup', this.myHide);
  }
...

need-popup-component.vue

methods: {
  showPopup() {
    this.$popup.show({
      title: 'title',
      content: 'content',
      callback: this.okcallback
    }); 
  }
}

It seems to be works well, but i don't know is this correct. Is there any other way?


Solution

  • I was very surprised while reading your solution, but if you feel it simple and working, why not?

    I would do this:

    • Add a boolean property in the state (or any data needed for showing popup), reflecting the display of the popup
    • use mapState in App.vue to bring the reactive boolean in the component
    • use v-if or show in App.vue template, on the popup declaration
    • create a 'showPopup' mutation that take a boolean and update the state accordingly
    • call the mutation from anywhere, anytime I needed to show/hide the popup

    That will follow the vue pattern. Anything in state, ui components reflect the state, mutations mutates the state.

    Your solution works, ok, but it doesn't follow vue framework, for exemple vue debug tools will be useless in your case. I consider better to have the minimum of number of patterns in one app, for maintenance, giving it to other people and so on.