使用场景:
- 兄弟组件传参
- 非父子组件传参
注:父子组件传参也是可以的,但是因为父子组件传参比较简单,如果使用eventBus或者Vuex显得大材小用了
效果展示:
代码展示:
- 在utils中创建一个eventBus.js文件,用来导入导入vue实例对象
import Vue from 'vue';
export default new Vue();
- 既然叫事件车,那肯定就有个上车和下车的过程,我们在A组件上车
<template>
<div class="wrap">
<h2>这是A组件</h2>
{{ num }}
<hr />
<button @click="handleClick">向B组件传值</button>
</div>
</template>
<script>
import Bus from '../utils/bus'
export default {
name: "A",
data(){
return {
num: 0
}
},
methods: {
handleClick() {
Bus.$emit('abc', ++this.num)
}
}
}
</script>
<style lang="less" scoped>
.wrap{
width: 150px;
background: lightblue;
color: red;
line-height: 1;
}
</style>
- 在B组件中下车——在created阶段接收A组件传来的参数
<template>
<div class="wrap">
<h2>这是B组件</h2>
{{count}}
</div>
</template>
<script>
import Bus from '../utils/bus';
export default {
name: "B",
data(){
return {
count: 0
}
},
created(){
Bus.$on('abc', (e) => {
this.count = e
})
}
}
</script>
<style lang="less" scoped>
.wrap{
width: 150px;
background: lightcoral;
color: green;
line-height: 1;
}
</style>
动动手,其实也很简单~~