借用父组件

方法1:借用父组件实现平行组件间通信,子组件1先调用 emit 方法将参数传给父组件,父组件再通过 props 传递给子组件2。

总线 Bus

方法2:用事件总线 Bus 传值,父组件引入子组件,子组件需要传值的用 Bus.emit(),接收方用 Bus.on()

//父组件
<template>
    <div class="father">
        <ChildOne />
        <ChildTwo />
    </div>
</template>
<script>
import ChildOne from "./ChildOne";
import ChildTwo from "./ChildTwo"
export default {
    name :"Father",
    components: { ChildOne, ChildTwo }
};
<template>
    <div class="childOne">
    <h1>我是子组件1</h1>
        <button @click="changeTwo">点击我改变子组件2的值</button>
    </div>
</template>
 
<script>
import Bus from "@/bus/bus"
export default {
    name:"ChildOne",
    methods:{
        changeTwo(){
            Bus.$emit("changeName","参数(选填)")
        }   
    }  
}
</script>
<template>
    <div class="childTwo">
        <h1>我是子组件2</h1>
        <p>{{name}}</p>
    </div>
</template>
 
<script>
import Bus from "@/bus/bus"
export default {
    name:"childTwo",
    data(){
        return {
            name: "zhangsan",
        };
    },
    mounted(){
        Bus.$on("changeName",(data) => { this.name = data });
    }
</script>