首先, 总结一下全局通信事件, 个人更喜欢
VUE不同页面间的传值之EventBus
传递的值不显示
EventBus称为事件总线。
EventBus就如同公交车,通过$emit
让乘客(即所要传递的值)在发出地上车,在目的地通过$on
使乘客下车。
通常有两种方式去对它进行使用:
方法一:
首先在src文件下创建EventBus.js并将其导出,以便其它模块可以使用或者监听它。
import Vue from 'vue'
export const EventBus = new Vue()
发送事件
import { EventBus } from "./eventbus.js";
//在$emit中第一个参数为自定义事件名,第二个参数为要传递的值
EventBus.$emit("eventName", this.name);
接收事件
import { EventBus } from "./eventbus.js";
//注意此处的值第一个参数要与发出组件中$emit的第一个参数相同
EventBus.$on("eventName", (value) => {
this.newname = value;
})
方法二:
直接在main.js文件中加入
Vue.prototype.$EventBus = new Vue()
在页面中直接使用
this.$EventBus.$emit("事件名", 参数) // 发射
this.$EventBus.$on("事件名", (参数) => { // 接收
this.newNname = 参数
})
说说具体的坑:
在这有两种情况:
第一种:
就是兄弟组件 , 当发射和接收页面拥有共同的父组件, 在同一个页面当中那你随便使用, 按照上面的法一, 法二来就行了.
第二种:
就是两个完全不相关的路由页面,使用eventBus也是可以拿到相应的数据,在created中接收但是死活就是没法渲染到页面上, 这里涉及到生命周期的问题:
最先开始以为是页面刷新,将数据也刷新了,没有传递过来。然后用了keep-alive, 结果然并卵。只能百度,了解到与组件的生命周期有关。
新组件:beforeCreate
↓
新组件:created
↓
新组件:beforeMount
↓
旧组件:beforeDestroy
↓
旧组件:destroyed
↓
新组件:mounted
由此可以了解到你要在新组件dom挂载前将值传出来。 — > 这块还没缕清, 按理说我通过点击事件去发射emit, 肯定是要早于生命周期创建mounted之前的, 不会渲染不出来啊!
直接上解决方案: 在发射页面, 下面二选一就行了:
// 1. destroyed() {
// this.clickDetailAddress();
// },
2. beforeDestroy () {
this.clickDetailAddress();
}
也贴一下个人具体业务代码, 主要想展示一下click事件, 为什么直接click发射出去的数据在$on监听页面接收到后死活渲染不了页面?
<template>
<div id="fill_community">
<input type="text" v-model="street">
<div class="but_wrapper">
<van-button type="info" size="large" @click="clickDetailAddress">确认</van-button>
</div>
</div>
</template>
<script>
export default {
name: 'FillCommunity', // 填写详细地址
data() {
return {
street: ''
}
},
beforeDestroy() {
this.clickDetailAddress()
},
methods: {
clickDetailAddress() {
this.$eventBus.$emit('emitDetailAddress', this.street)
this.$router.back()
// this.$router.push({
// path: '/productPAJCX/details/index',
// query: {
// detailAddress: this.detailAddress
// }
// })
}
}
}
</script>
然后$on
接收页面, 同样二选一:
// 1. beforeMount () {
// EventBus.$on("emitDetailAddress", (message) => {
// this.newname = message;
// });
// },
2. created () {
EventBus.$on("emitDetailAddress", (message) => {
this.newname = message;
});
}
这样取到的值就可以实时显示了.
总结一下: 接收页面都无所谓, 大多都是在creatd中去接收数据, 就是发射的时候需要在生命周期destroyed/beforeDestroy
再去调用一下发射事件