源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-05-23 18:03 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:vue中的event bus非父子组件通信解析
有时候非父子关系的组件也需要通信。在简单的场景下,使用一个空的Vue实例作为中央事件总线:
var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
 // ...
})
在更多复杂的情况下,你应该考虑使用专门的 [url=https://vuefe.cn/v2/guide/state-management.html]状态管理模式[/url].就是用到了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>
效果图如下: [img]http://files.jb51.net/file_images/article/201710/2017102783045931.png?201792783054[/img] 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部