2
votes

From the Vue guide Composing Components, instead of mutating the data in a child component, an event should be emitted to parent component/instance to do the mutation. However, Vue's event can only propagate up one level. For nested components, my current implementation is like below: enter image description here

When the client does an action in grandchild component

=> grandchild component has a method to emit an event to child component

=> child component has a method to re-emit the event to parent component

=> parent component has a method to mutate the data

This type of implementation is very tedious when nested components have more nesting.

Can someone tell me if this implementation is usual for nested components? However, this is really tedious and hard to maintain. If no, what implementation is not anti-pattern to Vue and also easy to maintain?

2
When you have too many nested components, then you can consider using vuexVamsi Krishna

2 Answers

2
votes

To handle this I usually setup another instance of Vue to act as an eventhub.

first in your main js file:

window.eventHub = new Vue();

and then in the components:

//component emitting event:
eventHub.$emit('shout', this.target);


//component listening to event
eventHub.$on('shout', function(){alert("EVENT EVENT");});
1
votes

When applications increase in complexity, one of the common ways to manage the situation is to turn to a state management system.

Here is an example of a very basic state management system.

const store = {
  state:{
    message: "Hello World"
  },
  changeMessage(newMessage){
      this.state.message = newMessage               
  }
}

Vue.component("grand-child",{
  template:`
    <div><button @click="sayHello">Say Hello</button></div>
  `,
  methods:{
    sayHello(){
      store.changeMessage("Hello from grand child!")
    }
  }
})

Vue.component("child", {
  template: `
    <grand-child></grand-child>
  `
})

new Vue({
  el:"#app",
  data:{
    state: store.state
  }
})

And here is an example of it working. The basic idea is you offload the management of state to an external entity, and your Vue code becomes primarily about rendering the state and telling the state management system about actions from the user or changes that need to be made. The documentation talks about this kind of system here.

You can go a long way with a home grown solution, but often projects grow in complexity to require a more formal method of state management, which is where the Vue ecosystem offers Vuex.

Personally I don't often find the need for the complexity that comes along with Vuex, but you might and many others do.