VUE_非父子组件间通信

一、在 main.js 中初始化根 Vue 之前,添加一个 data 对象,内写入一个名为 Event 的空 Vue 对象,也就是中央事件总线

new Vue({
	el: '#app',
	data:{
		Event: new Vue()
	},
	render: h => h(App)
})

二、在各组件中使用 Vue 的实例属性 $root 来访问我们当前组件树的根 Vue 实例,这样就可以使用

vm.$root.Event 来访问我们定义的事件发射器 Event
比如我在 Hello.vue 组件中想发送数据到 Vue.vue 组件中

<template>
    <div class="hello">
        <h3>我是 {{name}} 组件</h3>
        <button @click="send">发送数据到Vue组件中</button>
    </div>
</template>

<script>
export default {
    data(){
        return {
            name: 'Hello'
        }
    },
    methods:{
        send(){
            // 触发组件 Hello 中的事件
                           // $emit(事件名,数据)
            this.$root.Event.$emit('hello',this.name)
        }
    }
}
</script>

在 Vue.vue 组件中进行接收

<template>
    <div class="Vue">
        <h3>我是 {{name}} 组件</h3>
    </div>
</template>

<script>
export default {
    data(){
        return {
            name: ''
        }
    },
    mounted(){
        // 在组件 Vue 创建的钩子中监听事件
                        // $on(事件名,数据)
        this.$root.Event.$on('hello',name => {
            this.name = name
        })
    }
}
</script>

.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值