vue使用发布&订阅模式再非父子组件间传值

版权声明:欢迎交流讨论 https://blog.csdn.net/qq_37746973/article/details/82699257

Vue中可以通过广播的方式进行非父子组件间传值,具体方法如下

第一,在Vue的原型上挂载一个Vue实例。

Vue.prototype.bus = new Vue();

在methods中定义发布者方法

使用 this.bus.$emit 发布广播

methods:{
    broadcast: function() { //广播
        this.bus.$emit('change', this.selfContent);
    }
}

在mounted中定义订阅者方法

使用 this.bus.$on 订阅事件

mounted: function () {   //订阅
    var _this = this;
    this.bus.$on('change', function (msg) {    //订阅change事件
        _this.selfContent = msg;
    })
}

完整代码

<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <title>非父子组件间传值(Bus总线 / 发布订阅模式 / 观察者模式)</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>

<body>
    <h1>点击一个组件,他将改变其他组件(非父子关系)的内容</h1>
    <div id="app">
        <child :content="first"></child>
        <child :content="second"></child>
    </div>

    <script>
        Vue.prototype.bus = new Vue();
        Vue.component('child', {
            props: ['content'],
            data: function () {
                return {
                    selfContent: this.content
                }
            },
            template: '<div @click="broadcast">{{selfContent}}</div>',
            methods: {
                broadcast: function () {//广播
                    this.bus.$emit('change', this.selfContent);
                }
            },
            mounted: function () {   //接受
                var _this = this;
                this.bus.$on('change', function (msg) {
                    _this.selfContent = msg;
                })
            },
        });
        var vm = new Vue({
            el: '#app',
            data: {
                first: "Hu",
                second: "Yao"
            }
        })
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/qq_37746973/article/details/82699257