Vue中Event Bus的使用

使用场景:

  1. 兄弟组件传参
  2. 非父子组件传参
    注:父子组件传参也是可以的,但是因为父子组件传参比较简单,如果使用eventBus或者Vuex显得大材小用了

效果展示:

在这里插入图片描述

代码展示:

  1. 在utils中创建一个eventBus.js文件,用来导入导入vue实例对象
import Vue from 'vue';
export default new Vue();
  1. 既然叫事件车,那肯定就有个上车和下车的过程,我们在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>
  1. 在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>

动动手,其实也很简单~~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值