3👍
If you have a need for an event bus, there’s no harm in using one. The main problems people have with them are 1) that they pollute the global event space (obviously), 2) if relied upon too heavily can become cumbersome to track, and 3) risk collisions with event names or unintended side effects.
Vuex is a shared reactive state accessible anywhere throughout your application. Key word being reactive, don’t think you will be calling methods between components, i.e. component A calls a method defined in component B. Instead, component A will mutate a given property in the state tree which component B is observing (typically in a computed property or watcher).
For example:
// First.vue
<template>
<div>{{ myStoreProp }}</div>
</template>
...
computed: {
myStoreProp () {
return this.$store.getters['myModule/myStoreProp']
}
}
// Second.vue
<template>
<button @click="updateMyStoreProp('Hello from Second.vue')">Click Me</button>
</template>
...
methods: {
updateMyStoreProp (value) {
this.$store.commit('myModule/myStoreProp', value)
}
}
Now whenever Second.vue calls it’s updateMyStoreProp
function, the value committed to the store will reflect in First.vue’s template, in this case printing “Hello from Second.vue”.
- [Vuejs]-Search an array of words or a string with array of words using includes
- [Vuejs]-How to get id from a loop's item in vue.js?
1👍
You can use event bus to emit and listen event, but you should use vuex when your app become complex. Use vuex API subscribe
to implement event bus functionality using vuex. https://vuex.vuejs.org/api/#subscribe
Just simple step, you commit mutation
in component A, and use subscribe
to listen mutation in component B.