温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue中的event bus非父子组件通信解析

发布时间:2020-10-23 13:47:17 来源:脚本之家 阅读:129 作者:CURRY_zhao 栏目:web开发

有时候非父子关系的组件也需要通信。在简单的场景下,使用一个空的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>
<div id="todo-app">
<h2>todo app</h2>
<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>

效果图如下:

vue中的event bus非父子组件通信解析

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI