项目中有需求是两个页面频繁来回切换传值,最开始用的父子组件,但因为是父子组件导致页面只有一个返回事件,只要返回全部清空,so把子组件注册为路由利用eventbus进行传值。写法如下:
首先初始化在common.js中
import vue from "vue"
export const eventBus = new vue()
然后在main.js中注册
Vue.prototype.$eventBus = new Vue()
然后是在使用页面引入
import { eventBus} from '@/common/eventBus.js'
在A页面发送值
beforeDestroy() {
eventBus.$emit('listData',{batchInfoList:this.copyList,index:this.parentIndex})
}
在B页面接收
onLoad(options) {
eventBus.$on('listData', (data) => {
this.detailData.advanceProMList[data.index*1].batchInfoList = data.batchInfoList
})
}
大概用法就是这样,我是在uniapp中写的 ,vue用法也一致 只是生命周期会有出入