vue中的event bus非父子組件通信解析
更新時間:2017年10月27日 08:28:46 作者:CURRY_zhao
本篇文章主要介紹了 vue中的event bus非父子組件通信解析 ,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
有時候非父子關(guān)系的組件也需要通信。在簡單的場景下,使用一個空的Vue實例作為中央事件總線:
var bus = new Vue() // 觸發(fā)組件 A 中的事件 bus.$emit('id-selected', 1) // 在組件 B 創(chuàng)建的鉤子中監(jiān)聽事件 bus.$on('id-selected', function (id) { // ... })
在更多復(fù)雜的情況下,你應(yīng)該考慮使用專門的 狀態(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>
效果圖如下:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
在vue中實現(xiàn)給每個頁面頂部設(shè)置title
這篇文章主要介紹了在vue中實現(xiàn)給每個頁面頂部設(shè)置title,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07vite2.x實現(xiàn)按需加載ant-design-vue@next組件的方法
這篇文章主要介紹了vite2.x實現(xiàn)按需加載ant-design-vue@next組件的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03