Vue bus

bus主要实现组件之间的通信,较于组件之间的子传父,父再传另一子组件方便了很多

首先创建一个bus.js

import Vue from 'vue'
const bus = new Vue()
export default bus

父页面

<template>
  <div class="demo-wrapper">
    <comA />
    <comB />
  </div>
</template>

<script>
import comA from "./componentA";
import comB from "./componentB";
export default {
  components: {
    comA,
    comB,
  },
};
</script>

组件A

<template>
  <div>
    <button @click="handleClick">点我修改B的值</button>
  </div>
</template>

<script>
import bus from "@/utils/bus";
export default {
  data() {
    return {};
  },
  methods: {
    handleClick(){
      bus.$emit('busChange','A传递给B的值')
    },
  },
};
</script>

<style>
</style>

组件B

<template>
  <div></div>
</template>

<script>
import bus from "@/utils/bus";
export default {
  data() {
    return {};
  },
  mounted() {
    bus.$on("busChange", (e) => {
      console.log(e);
    });
  },
  methods: {},
};
</script>

<style>
</style>

以上简单的功能就实现了

接下来进行进一步的封装,能够更方便的去使用它

vue-bus.js

const install = function(Vue) {
    const Bus = new Vue({
        methods: {
            emit (event, ...args) {
                this.$emit(event, ...args);
            },
            on (event, callback) {
                this.$on(event, callback);
            },
            off (event, callback) {
                this.$off(event, callback);
            },
        }
    })
    Vue.prototype.$bus = Bus;
}

export default install;

在main.js中引用:

import VueBus from './vue-bus';
Vue.use(VueBus);

接在来就可以在项目中使用了

this.$bus.on('busChange',(e)=>{
	
});

this.$bus.emit('busChange','要传的值,也可以是方法')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值