vue:兄弟组件传参

vue父子组件可以通过 props 和 $emit进行传参

兄弟组件呢?

vue兄弟组件数据传递需要借助事件车,需要利用一个事件车bus进行传递数据

首先创建一个vue实例,让兄弟组件共同用一个事件

然后传递数据方,通过一个事件触发bus.$emit(方法名,传递的数据)

然后数据接收方,通过created(){}进行触发bus.$on(方法名,function(接收数据的参数){用该组件的数据接收传递过来的数据}),此时函数中的this已经发生改变,可以使用箭头函数方式写回调函数


具体案例如下

我们可以单独创建一个event.js充当中间实例bus

import Vue from 'vue'
export default new Vue()

这个是父组件home.vue

<template>
    <div>
        我是首页
        <component-a></component-a>
        <component-b></component-b>
    </div>
</template>

<script>
import comA from './a'
import comB from './b'
export default {
    components:{
        componentA:comA,
        componentB:comB
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>

</style>

兄弟组件a.vue

<template>
    <div>
        {{aDate}}
    </div>
</template>

<script>
import eventVue from './event.js'
export default {
    data(){
        return {
            aDate:'组件A的值'
        }
    },
    created(){
        this.aBtn()
    },
    methods:{
        aBtn(){
            eventVue.$on('FunB',(message) => {           //这里要用箭头函数,要不this指向有问题
                this.aDate = message
            })
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>

</style>

兄弟组件b.vue

<template>
    <div>
        <span class="componentB" @click="clickB">b组件</span>
    </div>
</template>

<script>
import eventVue from './event.js'

export default {
    data(){
        return {
            bDate:'B组件内容'
        }
    },
    methods:{
        clickB(){
            eventVue.$emit('FunB',this.bDate)
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.componentB{
    width: 200px;
    height: 100px;
    background: #000000;
    color: #ffffff;
    line-height: 100px;
    text-align: center;
    display: block;
}
</style>

效果如下:

'组件A的值'和'b组件'两个是兄弟组件

点击'b组件'按钮之前,页面如下


点击'b组件'按钮之后,原先‘组件A的值’变为‘B组建内容’,说明兄弟数据传递成功,页面如下


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值