Vue2 改变来自嵌套组件的数据

Vue2 mutating data from nested component

来自 Vue 指南 Composing Components,而不是改变子组件中的数据,应该向父组件 component/instance 发送一个事件来进行改变。但是,Vue 的事件只能向上传播一层。对于嵌套组件,我当前的实现如下所示:

当客户端在孙组件中执行操作时

=> 孙子组件有一个方法可以向子组件发出事件

=> 子组件有一个方法可以将事件重新发送给父组件

=>父组件有一个改变数据的方法

当嵌套组件嵌套较多时,这种实现方式非常繁琐

谁能告诉我这种实现是否适用于嵌套组件?但是,这确实很繁琐且难以维护。 如果不是,什么实现既不是 Vue 的反模式又易于维护?

为了处理这个问题,我通常设置另一个 Vue 实例作为事件中心。

首先在您的主 js 文件中:

window.eventHub = new Vue();

然后在组件中:

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


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

当应用程序复杂性增加时,管理这种情况的一种常见方法是转向状态管理系统。

这是一个非常基本状态管理系统的示例。

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
  }
})

这里是 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

您可以使用自己开发的解决方案走很长的路,但项目通常会变得越来越复杂,需要更正式的状态管理方法,这正是 Vue 生态系统提供的 Vuex

就我个人而言,我并不经常发现需要 Vuex 带来的复杂性,但您可能和许多其他人一样