一、事件车

1、兄弟组件之间传值要借助事件车,通过事件车的方式传递数据。
2、中央事件总线(通俗讲就是:eventBus事件车)的实质就是创建一个vue实例,通过一个空的vue实例作为桥梁实现vue组件间的通信。它是实现非父子组件通信的一种解决方案。
3、作用:实现非父子组件之间的数据传递。
4、传递数据方,通过一个事件触发bus.$emit(方法名,传递的数据)。
5、接收数据方

接收数据方,通过mounted(){
	bus.$on(方法名,function(接收数据的参数){
		//用该组件的数据接收传递过来的数据
		//此时函数中的this已经发生了改变,可以使用箭头函数。
	})
}
二、实例如下
1、创建事件车文件,eventBus.js

eventBus.js

import Vue from 'vue'
export default new Vue()
2、我们需要做的是将 componentA 中的数据传输到componentB中,componentA与componentB为兄弟组件!

传输方: componentA

//1、引入 eventBus.js 文件
import eventBus from '../eventBus.js'

//2、 在 methods 中定义函数
export defalut {
	methods: {
		add() {
			eventBus.$emit('pass', 'componentA参数')
		}
	}
}

接收方:componentB

//1、引入 eventBus.js 文件
import eventBus from '../eventBus.js'

//2、 在 created 生命周期中接收
export defalut {
	created() {
		//此处的 pass 与 componentA 中定义的emit事件一致。
		eventBus.$on('pass', (data)=>{
			console.log(data) //componentA参数
		})
	}
}

注意:如果 $on 多次触发,解决办法就是在 beforeDestroy 或 destroy 中将事件销毁,使用 $off()。

	beforeDestroy () {
      bus.$off('pass')
    },

还有其它的两种方法,分别是 vuex、和 子 -> 父 -> 子。

Logo

前往低代码交流专区

更多推荐