首頁  >  文章  >  web前端  >  vue中的event bus非父子組件通訊詳解

vue中的event bus非父子組件通訊詳解

小云云
小云云原創
2018-01-02 10:16:062375瀏覽

本文主要介紹了 vue中的event bus非父子元件通訊解析 ,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧,希望能幫助大家。

有時候非父子關係的元件也需要溝通。在簡單的場景下,使用空的Vue實例作為中央事件匯流排:


var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
 // ...
})

在更複雜的情況下,你應該考慮使用專門的狀態管理模式.就是用到了vuex

eventBus是作為兄弟關係的元件之間的通訊中介。

程式碼範例:


<!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:[&#39;A&#39;,&#39;B&#39;,&#39;C&#39;]
}
},
created:function () {
this.$on(&#39;add&#39;, this.addTodo)
this.$on(&#39;delete&#39;, this.deleteTodo)
},
beforeDestroy:function () {
this.$off(&#39;add&#39;, this.addTodo)
this.$off(&#39;delete&#39;, 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:&#39;&#39;
}
},
methods:{
add:function(){
eventHub.$emit(&#39;add&#39;, this.newtodo)
this.newtodo = &#39;&#39;
}
}
}
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(&#39;delete&#39;,i)
     }
     }
}
var app= new Vue({
el:&#39;#todo-app&#39;,
components:{
newTodo:newTodo,
todoList:todoList
}
})
</script>
</body>
</html>

效果圖如下:

相關推薦:

vue中eventbus被多次觸發如何解決

JS中this與event的區別詳解

guava eventbus實例程式碼詳解

#

以上是vue中的event bus非父子組件通訊詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn