Vue兄弟组件间通信

本文介绍如何使用事件中心实现Vue中兄弟组件间的通信。通过创建事件中心,并利用$on监听事件,$emit触发事件,$off销毁事件的方式实现跨组件的数据交互。

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

兄弟组件间通信通过事件中心的概念进行相关通信

在这里插入图片描述

1、创建事件中心
var hub = new Vue()
2、监听事件和销毁事件

hub.$on('eventName',functionEvent);//两个参数,一个事件名称,一个函数调用事件
hub.$off('eventName');
3、触发事件
hub.$emit('eventName');
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
    <title>兄弟组件相互通信</title>

</head>

<body>
    <div id="app">
        <button-a></button-a>
        <button-b></button-b>
        <button-c></button-c>
    </div>
</body>
<script>
    // 创建事件中心
    var hub = new Vue();
    // 创建全局组件A
    Vue.component('button-a', {
        data: function() {
            return {
                name: '组件A: ',
                count: 0
            }
        },
        template: '<div><div style="cursor: pointer;" @click="handle">{{name}} {{count}}</div> <div> . </div> </div>',
        methods: {
            handle: function() {
                // 触发事件
                hub.$emit('component-b', 2);
            }
        },
        // 挂载完毕
        mounted: function() {
            // 添加监听事件和函数 要用箭头函数否则取不到值
            hub.$on('component-a', (value) => {
                this.count += value;
            });
        }
    });
    // 创建全局组件B
    Vue.component('button-b', {
        data: function() {
            return {
                name: '组件B:',
                count: 0
            }
        },
        template: '<div> <div style="cursor: pointer;" @click="handle">{{name}} {{count}}</div> </div>',
        methods: {
            handle: function() {
                // 触发事件
                hub.$emit('component-a', 2);
            }
        },
        // 挂载完毕
        mounted: function() {
            // 添加监听事件和函数 要用箭头函数否则取不到
            hub.$on('component-b', (value) => {
                this.count += value;
            });
        }
    });
    // 创建全局组件C
    Vue.component('button-c', {
        data: function() {

        },
        template: '<div> <input type="button" @click="deleteEvent" value="事件销毁" /> <div>',
        methods: {
            deleteEvent() {
                // 销毁事件
                hub.$off('component-a');
                hub.$off('component-b');
                alert("事件销毁成功!")
            }
        }
    })
    var vm = new Vue({
        el: '#app',
        data: {

        },
        methods: {

        }
    })
</script>

</html>

<style>

</style>
效果图如下所示:(点击A组件B组件进行响应)

请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值