//兄弟组件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)