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

本文介绍在Vue中如何通过广播方式实现非父子组件间的传值。具体包括在Vue原型上挂载实例、定义发布者与订阅者方法,以及如何在组件中使用$emit和$on实现事件的发布与订阅。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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/vue@2.5.17/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>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值