vue非父子组件通信(EventBus)

之前在使用vue开发后台管理系统时,头部按钮点击,左侧菜单导航展开和收缩的功能,由于菜单导航和头部是两个组件,所以这个时候就涉及到非父子组件通信。

有必要思考两个问题:

1. Vue 中非父子组件通信的方法有哪些

答:常用的方法有 EventBus 和 Vuex(Vuex暂不说明,两者使用场景都可以查看官方文档)。

2. EventBus 实现非父子组件通信的原理是什么

答:通过实例化一个Vue对象( 比如bus = new Vue() )作为母线,在组件中通过事件将参数传递出去( bus.$emit(event, [...args]) ),然后在其他组件中再通过bus( 这里按照刚前面实例化Vue对象后的叫法 )来监听此事件并接受参数( bus.$on(event, callback) )。

PS: 共用同一个Vue的实例( new Vue() ),通过此实例进行事件传递参数,在其他组件中监听此事件并且接收参数实现通信。

例子(非上面的导航菜单功能):

bus.js (实例化一个Vue对象)

/**
 * 使用 EventBus
*/
import Vue from 'vue'

const bus = new Vue()

export default bus

组件Hello.vue

<template>
  <div class="hello">
    <h1>参数:{{ number }}</h1>
    <button @click="sendParam()">发送</button>
  </div>
</template>
<script>
import bus from './bus'
export default {
  data () {
    return {
      number: 123
    }
  },
  methods: {
    sendParam () {
      bus.$emit('getParam', this.number)
    }
  }
}
</script>

组件World.vue

<template>
  <div class="hello">
    <h1>接受参数{{ number }}</h1>
  </div>
</template>
<script>
import bus from './bus'
export default {
  data () {
    return {
      number: 0
    }
  },
  created () {
    bus.$on('getParam', param => {
      this.number = param
    })
  },
  beforeDestroy () {
    bus.$off('getParam')
  }
}
</script>

组件Home.vue (同时引入Hello.vue组件和World.vue组件)

<template>
  <div class="home">
    <hello></hello>
    <world></world>
  </div>
</template>

<script>
import Hello from '@/components/Hello'
import World from '@/components/World'
export default {
  name: 'Home',
  data () {
    return {
    }
  },
  components: {
    Hello,
    World
  }
}
</script>

效果图展示:

传递参数前:


image.png

传递参数后:


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容