vue非父子组件间通信

有时候非父子关系的组件也需要通信。在简单的场景下,使用一个空的Vue实例作为中央事件总线:

有时候非父子关系的组件也需要通信。在简单的场景下,使用一个空的 Vue 实例作为中央事件总线:

var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
// ...
})

在更多复杂的情况下,你应该考虑使用专门的 状态管理模式.就是用到了vuex

eventBus是作为兄弟关系的组件之间的通讯中介。

代码示例:

<!DOCTYPE html>
<html>
<head>
<title>eventBus</title>
<script src="http://cdn.jsdelivr.NET/vue/1.0.28/vue.min.js"></script>
</head>
<body>
<div id="todo-app">
<h1>todo app</h1>
<new-todo></new-todo>
<todo-list></todo-list>
</div>
<script>
var eventHub = new Vue( {
data(){
return{
  todos:['A','B','C']
}
},
created:function () {
  this.$on('add', this.addTodo)
  this.$on('delete', this.deleteTodo)
},
beforeDestroy:function () {
  this.$off('add', this.addTodo)
  this.$off('delete', this.deleteTodo)
},
methods: {
  addTodo: function (newTodo) {
    this.todos.push(newTodo)
  },
  deleteTodo: function (i) {
    this.todos.splice(i,1)
  }
}
})
var newTodo = {
template:`<div><input type="text" autofocus v-model="newtodo"/><button @click="add">add</button></div>`,
data(){
  return{
    newtodo:''
  }
},
methods:{
  add:function(){
    eventHub.$emit('add', this.newtodo)
    this.newtodo = ''
  }
}
}
var todoList = {
  template:`<ul><li v-for="(index,item) in items">{{item}}
            <button @click="rm(index)">X</button></li>
            </ul>`,
      data(){
            return{
              items:eventHub.todos
            }
      },
       methods:{
            rm:function(i){
              eventHub.$emit('delete',i)
            }
       }
}
var app= new Vue({
  el:'#todo-app',
  components:{
    newTodo:newTodo,
    todoList:todoList
  }
})
</script>
</body>
</html>

效果图如下:

原文地址:https://www.cnblogs.com/cina33blogs/p/6769523.html