vue中的event bus非父子組件通信解析
有時(shí)候非父子關(guān)系的組件也需要通信。在簡(jiǎn)單的場(chǎng)景下,使用一個(gè)空的Vue實(shí)例作為中央事件總線:
var bus = new Vue() // 觸發(fā)組件 A 中的事件 bus.$emit('id-selected', 1) // 在組件 B 創(chuàng)建的鉤子中監(jiān)聽(tīng)事件 bus.$on('id-selected', function (id) { // ... })
在更多復(fù)雜的情況下,你應(yīng)該考慮使用專門(mén)的 狀態(tài)管理模式.就是用到了vuex
eventBus是作為兄弟關(guān)系的組件之間的通訊中介。
代碼示例:
<!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>
效果圖如下:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
在vue中實(shí)現(xiàn)給每個(gè)頁(yè)面頂部設(shè)置title
這篇文章主要介紹了在vue中實(shí)現(xiàn)給每個(gè)頁(yè)面頂部設(shè)置title,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07vite2.x實(shí)現(xiàn)按需加載ant-design-vue@next組件的方法
這篇文章主要介紹了vite2.x實(shí)現(xiàn)按需加載ant-design-vue@next組件的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03如何解決uni-app編譯后?vendor.js?文件過(guò)大
這篇文章主要介紹了如何解決uni-app編譯后?vendor.js?文件過(guò)大的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02