vue同胞组件通讯解决方案(以下为一种另外可用vuex解决)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="vue2.2.js"></script>
    </head>
    <body>
        <div id="app">
            <aa></aa>
            <hr />
            <bb></bb>
        </div>
        <script type="text/javascript">
            // 注册一个空的 Vue 实例,作为 ‘中转站’
            var eventBus = new Vue();
            //A组件
            Vue.component("aa", {
                template: "<button @click='addBar'>点击</button>",
                data: function() {
                    return {
                        
                    }
                },
                methods: {
                    addBar: function() {
                        //让B组件执行监听事件
                        eventBus.$emit('doCount')
                    }
                }
            });
            //B组件
            Vue.component("bb", {
                template: "<div>{{count}}</div>",
                data: function() {
                    return {
                        count: 0
                    }
                },
                //在组件创建的钩子函数中监听事件
                mounted: function() {
                    var _this = this;
                    eventBus.$on("doCount", function() {
                        _this.count ++;//+=1
                    });
                }
            });
            new Vue({
                el: "#app"
            });
        </script>
    </body>
</html>

猜你喜欢

转载自www.cnblogs.com/lhl66/p/8974309.html