1.eventBus适用场景
目前了解到的eventbus一般比较适用于兄弟组件之间的通信; 两个兄弟组件有一个共同的父组件;
注意事项:
1 eventbus需要先通过emit触发;
2 触发事件的组件在销毁时,建议在destoryed生命周期中通过$off销毁事件
2. 代码示例-亲测有效
- 兄弟组件A
<template>
<div class="sibling-con">
<h1>sibling</h1>
<el-button @click="submitData">submit Data</el-button>
</div>
</template>
<script>
export default {
name: 'sibling',
data () {
return {
name: 'hello world'
}
},
methods: {
submitData() {
this.$EventBus.$emit('handleName', this.name); // 触发点击事件时,通过$emit向兄弟组件传递值;
}
},
destroyed() {
this.$EventBus.$off('handleName'); // 组件销毁之前销毁监听事件
}
}
</script>
<style lang="scss" scoped>
.sibling-con {
height: 20%;
background: #fff;
}
</style>
- 兄弟组件B
<template>
<div class="sibling1-con">
<h1>sibling1</h1>
<p>{{ receiveValue }}</p>
</div>
</template>
<script>
export default {
name: 'sibling1',
data () {
return {
receiveValue: '',
}
},
created () {
// 兄弟组件中注册handleName事件,从而获取到传递的值;
this.$EventBus.$on('handleName', (params) => {
console.log('params: ', params);
this.receiveValue = params;
})
}
}
</script>
<style lang="scss" scoped>
.sibling1-con {
height: 20%;
background: #fff;
}
</style>
- 公用父组件
<template>
<div class="common-con">
<h1>common</h1>
<p>子组件通过$emit传递的值: {{siblingEmitVale}}</p>
<Sibling></Sibling>
<Sibling1></Sibling1>
</div>
</template>
<script>
import Sibling from './sibling.vue';
import Sibling1 from './sibling1.vue';
export default {
name: 'common',
components: {
Sibling,
Sibling1,
},
data () {
return {
siblingEmitVale: '',
}
},
created () {
// 在父组件中也可以通过eventBus接收到子组件中的传值
this.$EventBus.$on('handleName', (params) => {
console.log('params: ', params);
this.siblingEmitVale = params;
})
}
}
</script>
<style lang="scss" scoped>
.common-con {
height: 100%;
background: #fff;
}
</style>
-
页面效果
点击触发
网友评论