Home > Article > Web Front-end > How event bus non-parent-child components communicate with each other
This time I will show you how event bus non-parent and child components communicate with each other. What are the precautions for event bus non-parent and child components to communicate with each other? Here is a practical case, let’s take a look.
Sometimes components that are not in a parent-child relationship also need to communicate. In a simple scenario, use an empty Vue instance as the central Event bus:
var bus = new Vue() // 触发组件 A 中的事件 bus.$emit('id-selected', 1) // 在组件 B 创建的钩子中监听事件 bus.$on('id-selected', function (id) { // ... })
In more complex cases, you should consider using a dedicated state management mode. That is using vuex
eventBus is a communication intermediary between components that act as brothers.
Code example:
<!DOCTYPE html> <html> <head> <title>eventBus</title> <script src="http://cdn.jsdelivr.net/vue/1.0.28/vue.min.js"></script> </head> <body> <p id="todo-app"> <h1>todo app</h1> <new-todo></new-todo> <todo-list></todo-list> </p> <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:`<p><input type="text" autofocus v-model="newtodo"/><button @click="add">add</button></p>`, 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>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How does JS detect scripts in the browser
Popup popup box binding add data event ( Detailed explanation of steps)
The above is the detailed content of How event bus non-parent-child components communicate with each other. For more information, please follow other related articles on the PHP Chinese website!