vue2.0开发笔记

非父子组件通信(实例demo)

2017-10-15  本文已影响10人  iqing2012

有时候,非父子关系的两个组件之间也需要通信。在简单的场景下,可以使用一个空的 Vue 实例作为事件总线:
var bus = new Vue()

// 触发组件 A 中的事件
bus.$emit('id-selected', 1)

// 在组件 B 创建的钩子中监听事件

bus.$on('id-selected', function (id) {
// ...
})

在复杂的情况下,我们应该考虑使用专门的状态管理模式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../vue.js">
    </script>
</head>
<body>
<div id="app">
    <foo></foo>
    <bar></bar>
</div>
<script>
//使用一个空的实例来作为中央事件总线。
    var eventBus=new Vue({});
    Vue.component('foo',{
        template:'<div><p>the count of foo is {{fooCount}}</p>' +
                '<button @click="emitevent">Add bar\'s count</button></div>',
        data:function () {
            return {fooCount:0}
        },
        methods:{
            emitevent:function () {
//这里要使用中央事件发送信号。
                eventBus.$emit('emitevent');
            }
            }
    });
    Vue.component('bar',{
        template:'<div><p>the count of bar is {{barCount}}</p>' +
                '<button >B</button></div>',
        data:function () {
            return {barCount:0}
        },
        mounted:function () {
//这里要使用中央事件接受信号。并且是在组件挂载完成后。
            var _this=this;
            eventBus.$on('emitevent',function () {
                _this.barCount+=1; });
        }
    });
    var app=new Vue({
        el:'#app',

    })
</script>
</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读