1. 首先有两个兄弟组件
2. 在scr目录下面创建 common 文件夹 再在common目录下创建 bus.js文件,具体如下
然后 bus.js 的内容如下
import Vue from "vue";
export default new Vue;
没错,只需要这些
3. 传值 如何传过去?
3.1 在BrotherA 组件引入 bus
3.2 我们在 BrotherA 点击按钮传值过去
3.3 代码如下
<template>
<div>
foots组件
<button @click="changClick">传值过去</button>
</div>
</template>
<script>
import bus from "@/common/bus"
export default {
data() {
return {
str:"我要传值给你"
};
},
methods: {
changClick () {
//toHandls我们自己定义的事件 this.str需要在 BrotherA传过去的数据 其实跟 this.$emit() 写法差不多,只不过把this换了
bus.$emit("toHandls",this.str)
}
},
};
</script>
<style scoped lang="less">
</style>
4. 接收 如何接收?
4.1 首先第一步也是要引入 bus
4.2 在Mounted这个生命周期函数 获取
4.3 代码如下
<template>
<div>
handls组件
我来展示 --- {{msg}} 的值
</div>
</template>
<script>
import bus from "@/common/bus"
export default {
props: {
},
components: {
},
data() {
return {
msg:''
};
},
mounted() {
// 这个 data 是 BrotherA 传过来的数据 这里负责接收
bus.$on("toHandls",(data)=>{
this.msg=data
})
},
};
</script>
<style scoped lang="less">
</style>
5. 兄弟组件之间传值的数据