This article mainly introduces the communication analysis of event bus non-parent-child components in vue. The editor thinks it is quite good. Now I will share it with you and give it a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Sometimes components with non-parent-child relationships also need to communicate. In simple scenarios, 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 pattern .Is using vuex
eventBus is used as a communication intermediary between components in a sibling relationship.
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>
Related recommendations:
How to solve the problem of eventbus being triggered multiple times in vue
Detailed explanation of the difference between this and event in JS
Guava eventbus example code detailed explanation
The above is the detailed content of Detailed explanation of event bus non-parent-child component communication in vue. For more information, please follow other related articles on the PHP Chinese website!