Vue组件间数据交互

在这里插入图片描述
我们写一个例子演示一下,点击A下面的按钮时,B数字+1,点击B下面的按钮时,A数字+10:

<body>
    <div id="app">
        <test-a></test-a>
        <test-b></test-b>
    </div>
    <script>
        // 事件中心
        var hub = new Vue()

        // 组件a
        Vue.component('test-a', {
            data: function () {
                return {
                    num: 0
                }
            },
            template: `
                <div>
                    <div>A:{{ num }}</div>
                    <div>
                        <button @click="handle">Click</button>
                    </div>
                </div>
            `,
            methods: {
                // 触发事件
                handle: function () {
                    hub.$emit('b-plus', 1)
                }
            },
            mounted: function () {
                // 监听事件
                hub.$on('a-plus', (val) => {
                    this.num += val
                })
            }
        })

        // 组件b
        Vue.component('test-b', {
            data: function () {
                return {
                    num: 0
                }
            },
            template: `
                <div>
                    <div>B:{{ num }}</div>
                    <div>
                        <button @click="handle">Click</button>
                    </div>
                </div>
            `,
            methods: {
                // 触发事件
                handle: function () {
                    hub.$emit('a-plus', 10)
                }
            },
            mounted: function () {
                // 监听事件
                hub.$on('b-plus', (val) => {
                    this.num += val
                })
            }
        })

        var vm = new Vue({
            el: '#app',
            data: {

            },
            methods: {

            }
        })
    </script>
</body>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值