Vue(七)Vue中父子组件传参的高级用法【下】

一、eventBus(全局事件总线)

使用介绍

        EventBus又称为事件总线,可以使用它来进行组件之间通信。其实和vuex还是有些类似的,相当于所有组件共用一个事件中心,这个事件中心用来管理事件,当我们需要用到的时候就向事件中心发送或者接受事件。通过共享一个vue实例,使用该实例的$on以及$emit实现数据传递

使用场景

  • 隔代组件通信(父传子,子传父)
  • 兄弟组件通信

使用方法

        1、接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

methods(){
  demo(data){......}
}
......
mounted() {
  this.$bus.$on('xxxx',this.demo)
}

        2、提供数据:this.$bus.$emit('xxxx',数据)

        3、最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件

代码演示

 main.js

// 引入Vue
import Vue from 'vue'
// 引入App
import App from './App.vue'
// 引入Vue-router
import router from './router'
// 引入Vuex
import store from './store'
// 关闭Vue的生产提示
Vue.config.productionTip = false

new Vue({
    router,
    store,
    render: h => h(App),
    beforeCreate() {
        Vue.prototype.$bus = this //安装全局事件总线
    }
}).$mount('#app')

a组件(接收数据的)的生命周期钩子中添加事件到事件总线上 回调留在自身

<template>
  <div>
    <h1>我是A</h1>
    <hr>
    <h2>{{name}}</h2>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data:"兄弟传参",
      name:""
    }
  },
  mounted() {
    this.$bus.$on("hello", (e) => {
      console.log(e)
      console.log("我是MyChild组件,收到了数据", e);
      this.name=e
    });
  },
  beforeDestroy() {
    this.$bus.$off("hello");
  },
};
</script>

<style lang="scss" scoped>
</style>

然后在b组件(提供数据的)内触发事件总线上对应的事件(通过事件触发)

<template>
  <div>
    <h1>{{ name }}</h1>
    <button @click="sendStudentName">提交</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "我是B",
    };
  },
  methods: {
    sendStudentName() {
      this.$bus.$emit("hello", this.name);
    },
  },
};
</script>

<style lang="scss" scoped>
</style>

父组件:

<template>
  <div>
    <h1>我是父组件</h1>
    <my-brother></my-brother>
    <my-child></my-child>
  </div>
</template>

<script>
import MyBrother from "../components/MyBrother.vue";
import MyChild from "../components/MyChild.vue";
export default {
  components: { MyBrother, MyChild },
};
</script>

<style lang="scss" scoped>
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值