兄弟组件之间通信

编程入门 行业动态 更新时间:2024-10-09 15:25:06

兄弟<a href=https://www.elefans.com/category/jswz/34/1771375.html style=组件之间通信"/>

兄弟组件之间通信

兄弟没有共同的父级

创建空的Vue实例对象

// main.js
// 创建空的Vue实例
var eventBus = new Vue()
// 把Vue空实例挂载到Vue的原型上面
Vue.prototype.eventBus = eventBus

 创建a组件

<template>
    <div>
        我是child - a组件
        <button>传递数给b组件</button>
    </div>
</template>

 创建b组件

<template>
    <div>
        我是child - b组件
    </div>
</template>

在a组件中通过this.eventBus.$emit进行数据的传递  

this.eventBus.$emit('sendData', this.dataA) 

在b组件中通过this.eventBus.$on进行数据的监听接收

this.eventBus.$on('sendData', val => {
  this.receiveData = val
}) 

完整代码  

// main.js
// 创建空的Vue实例
var eventBus = new Vue()
// 把Vue空实例挂载到Vue的原型上面
Vue.prototype.eventBus = eventBus


<!-- a.vue -->
<template>
    <div>
        我是child - a组件
        <button @click="send">传递数给b组件</button>
    </div>
</template>
<script>
export default {
    data() {
        return {
            dataA: '我是a组件中的数据'
        }
    },
    methods: {
        send() {
            this.eventBus.$emit('sendData', this.dataA)
        }
    }
}
</script>


<!-- b.vue -->
<template>
    <div>
        我是child - b组件:{{ receiveData }}
    </div>
</template>
<script>
export default {
    data() {
        return {
            receiveData: ''
        }
    },
    // 声明周期:当组件加载完毕就执行,但是此时DOM节点还是虚拟的
    created() {
        // sendData:在a组件自定义事件名
        // function中的val就是形参,代表的就是a组件中传递过来的实参

        // 这里的this指向的是Vue实例
        this.eventBus.$on('sendData', val => {
            this.receiveData = val
        })
    }
}
</script>

 

总结

空实例方法比较简介,它有一个最大的特点就是不用分析组件的结构嵌套关系。你无需关注是否有共同的父级,因为这种通信方式是只要知道哪两个组件需要通信就可以了,一个组件设置$emit,另一个组件$on监听即可。如果项目大了用的多了容易乱套。这个问题需要Vuex(终极解决方案)来解决  

更多推荐

兄弟组件之间通信

本文发布于:2024-02-06 13:24:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1749481.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   兄弟   通信

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!