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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

CURRY_zhao   2021-03-28 我要评论
想了解vue中的event bus非父子组件通信解析的相关内容吗,CURRY_zhao在本文为您仔细讲解vue 非父子组件通信的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:vue,eventbus,vue,非父子组件通信,vue,非父子通信,下面大家一起来学习吧。

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

效果图如下:

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们