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中v-show添加表達(dá)式的問題(判斷是否顯示)
這篇文章主要介紹了關(guān)于Vue中v-show中添加表達(dá)式用于判斷是否顯示的問題,很多朋友經(jīng)常會遇到這樣的需求,有數(shù)據(jù)來源和標(biāo)簽類型兩行選項,需要實現(xiàn)點擊上面的某個數(shù)據(jù)來源時,標(biāo)簽類型自動切換功能,感興趣的朋友一起看看吧2018-03-03
vite?vue3?規(guī)范化與Git?Hooks詳解
這篇文章主要介紹了vite?vue3?規(guī)范化與Git?Hooks,本文重點討論?git?提交規(guī)范,結(jié)合示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-10-10
Vue3使用hooks函數(shù)實現(xiàn)代碼復(fù)用詳解
這篇文章主要介紹了Vue3使用hooks函數(shù)實現(xiàn)代碼復(fù)用詳解,Vue3的hook函數(shù)可以幫助我們提高代碼的復(fù)用性,?讓我們能在不同的組件中都利用hooks函數(shù)2022-06-06

