2

I probably do not want to use vuex for state management yet as it is probably overkill for now. I took a look at https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication. I am using single file component so I am not sure where do I define the shared bus such that both components will have reference to it.

var bus = new Vue()

ChildA.Vue

watch: {
  sideNav: (newValue) => {
    bus.$emit('sideNav-changed', newValue)
  }
}

ChildB.Vue

created () {
  bus.$on('sideNav-changed', data => {
    console.log(`received new value: ${data}`)
    // update own copy here
  })
}

Parent.Vue

<template>
  <childA>
  </childA>
  <childB>
  </childB>
</template>

I want to watch any changes of sideNav on ChildA and emit it to ChildB to update its own value.

tony19
  • 125,647
  • 18
  • 229
  • 307
Gavin
  • 2,784
  • 6
  • 41
  • 78

3 Answers3

1

Found the answer to it...

I declare it on the main.js

const bus = new Vue() // Single event hub

// Distribute to components using global mixin
Vue.mixin({
  data: function () {
    return {
      bus : bus 
    }
  }
})

And also change

watch: {
  sideNav: (newValue) => {
    bus.$emit('sideNav-changed', newValue)
  }
}

to

watch: {
  sideNav: function (newValue) {
    bus.$emit('sideNav-changed', newValue)
  }
}
Gavin
  • 2,784
  • 6
  • 41
  • 78
  • 1
    you "change" snippets are equivalent in this case. did you mean `this.bus.$emit`? – dfsq Aug 23 '17 at 07:41
  • Ah yes, not only that, notice the declaration of function. They are not the same – Gavin Aug 23 '17 at 08:24
  • 1
    I know that they are not the same, but they are equivalent in your case since you don't seem to use `this` so no point in changing to arrow function. – dfsq Aug 23 '17 at 09:33
0

Is this answer any good to you? You can do everything with events, but if you can avoid them, you should. You might not want vuex for now. That's where I am. But you want, right from the start, a store in global scope and reactive pipes. You "declare" the relationship between an element on the page and an item in the store, then basta. Vue takes care of the rest. You don't care about events.

bbsimonbb
  • 27,056
  • 15
  • 80
  • 110
0

The simplest way to do this would be to just attach it to the window i.e.

window.bus = new Vue()

Then it will be available in all of your components without the need to define a global mixin e.g. this will still work:

watch: {
  sideNav(newValue) {
    bus.$emit('sideNav-changed', newValue)
  }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Rwd
  • 34,180
  • 6
  • 64
  • 78