Vue基础知识——兄弟组件通讯(自定义事件的应用)

//兄弟组件1
<template>
    <div>brother1兄弟组件传过来的值为{{brotherData}}</div>
</template>
<script>
import event from './event'
export default {
    name: 'brotherVueOne',
    mounted() {
        this.onEvent()
    },
    data() {
        return {
            brotherData:''
        }
    },  
    methods: {
        getBrotherData(data) {
            console.log(data)
            this.brotherData = data;
        },  
        onEvent() {
            event.$on("brotherEvent",this.getBrotherData)
        }
    },
    beforeDestroy() {
        event.$off(this.getBrotherData)
    }
}
</script>
<style>
</style>
_________________________________________________________________________________________

//兄弟组件2
<template>
    <div @click="toBrother">brother2【点击传值给兄弟组件】</div>
</template>
<script>
import event from './event';
export default {
    name: 'brotherVueTwo',
    methods: {
        toBrother() {
            event.$emit("brotherEvent","from data of brother2")
        }
    }
}
</script>
<style>

</style>
—————————————————————————————————————————————————————————————————————————————————————————

//父组件
<template>
    <div>
        <brother-vue-one></brother-vue-one>
        <brother-vue-two></brother-vue-two>
    </div>
</template>
<script>
import BrotherVueOne from './Brother1.vue'
import BrotherVueTwo from './Brother2.vue'
export default {
    name: 'fatherVue',
    components: {
        BrotherVueOne,
        BrotherVueTwo
    }
}
</script>
<style>
</style>
—————————————————————————————————————————————————————————————————————————————————————————

//自定义事件的对象 ,文件名称 event.js

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

以上为完整代码,实际效果为点击兄弟组件2中的事件,将数据传给兄弟组件1。

关键要点总结:

1、定义一个普通的vue对象,并引用。注意区别于this,他们有一样的API。

2、在兄弟组件1中定义个onEvent的方法,方法中写上 event.$on("brotherEvent",this.getBrotherData) 。在this.getBrotherData 获取传入的值,并进行其他操作。

3、在兄弟组件2中定义一个点击事件,事件中写上event.$emit("brotherEvent","from data of brother2")。定义点击事件是为了触发$emit。brotherEvent 为兄弟组件1监听的事件。

4、在兄弟组件1中的beforeDestroy()中销毁定义的事件。避免内存泄漏

  event.$off(this.getBrotherData)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值