VUE兄弟组件传递数据(EventBus)

  1. 首先在main.js文件下添加:

//main.js
Vue.prototype.$EventBus = new Vue()
  1. 在左侧的组件,比如是组件Left,当中触发事件。

 // Left.vue
<template>
  <div>
    <button @click="sendMsg"><button>
  </div>
</template>
<script >
export default {
  data() {
    return {}
   },
  methods: {
    sendMsg() {
      this.$EventBus.$emit("send", "这里是数据");
    }
  }
}
</script>
  1. 在右侧的组件当中,Right组件,将事件挂载到组件上,然后等待该事件被触发。

//Right.vue
mounted() {
  this.$EventBus.$on("send", (data) => {
      alert(data);
  })
},
// 注意要在组件销毁之前把事件解绑
beforeDestory() {
  this.$EventBus.$off("send");
}

猜你喜欢

转载自blog.csdn.net/cdd9527/article/details/129588554