介绍
有的时候我们会遇到非父子组件之间需要通信, 用vuex
又比较重,这时候我们就可以用bus
来
实现非父子组件通信。即使用一个空的vue实例来负责这个工作。如果比较复杂的逻辑交互,还是去使用vuex
把
示意图
1 2 3 4 5 6 7 8 9
| var bus = new Vue() bus.$emit('id-selected', 1) bus.$on('id-selected', function (id) { })
|
实战
还是那之前的todo
, 我们通过bus
的方式写一次,这里 我们通过add
组件 向bus派发一个add
事件,把我们想添加的任务描述放在参数里;然后在todo
组件里,在created
钩子中监听了bus
的事件, 来执行我们的添加操作,
成功的将内容传入todo
完成通讯;最终实现效果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| <div id="app"> <add></add> <todo></todo> </div> <script> var bus = new Vue() Vue.component('add', { template: '<div><input v-model="content"> <button @click="add">增加任务</button></div>', data: function () { return { content: '' } }, methods: { add: function () { bus.$emit('add', {content: this.content}) } } }) Vue.component('todo', { template: '<ul><li v-for="(list, index) in lists">${list.content} <button @click="remove(index)">x</button></li></ul>', delimiters: ['${', '}'], data () { return { lists: [] } }, created: function () { bus.$on('add', this.add) }, methods: { add: function (obj) { this.lists.push(obj) }, remove: function(index) { this.lists.splice(index, 1) } } }) new Vue({ el: '#app' }) </script>
|