需求是这样的:当我点击 test 页面中的跳转按钮要跳转到 home 页面的时候,我希望 test 页面中的某些数据会传递到 home 页面;
但是 eventBus 有一些问题:
问题 1:第一次点击跳转的时候,home 页面接收不到数据;
问题 2:第二次点击跳转的时候,home 页面接收到 1 遍数据,第三次点击跳转的时候,home 页面接收了 2 遍数据,第四次点击跳转的时候,home 页面接收了 3 遍数据,依次增加。。
我的代码是这样的:
test 组件,发送数据的页面:
<template>
<div>
<button @click="click">go</button>
</div>
</template>
<script>
export default {
data() {
return {
data: 2333
};
},
methods: {
click() {
this.eventBus.$emit("msg", this.data);
this.$router.push("/home");
}
}
};
</script>
home 组件,接收数据的页面:
<template>
<div>
<button @click="$router.push('/test')">go</button>
</div>
</template>
<script>
export default {
data() {
return {};
},
mounted() {
this.eventBus.$on("msg", msg => {
console.log(msg);
});
}
};
</script>
解答
针对问题 1
明明写法没错,但是第一次跳转的时候却拿不到数据,于是我测试了一下从 test 页面跳转到 home 页面的生命周期:
可以清晰的看到,我们还在 test 页面的时候,点击跳转 $emit 发送数据,这时候 home 页面还没有生成,即 $on 根本接收不到数据。所以第一次跳转的时候拿不到数据。
解决办法
在 beforeDestroy() 或者 destroyed() 生命周期内使用 $emit 发送数据,因为这时候接收数据的页面已经 created 成功;
针对问题 2
我在上一篇博客《Vue事件总线 eventBus》中已经说明,用于发送数据的 $emit 和接收数据的 $on 不会自动销毁,所以我们需要每次都手动销毁:
destroyed() {
this.eventBus.$off("msg");
}
注意:两个页面都要用 $off 消除事件;
ok完结,撒花 🌺🌻🌼✨🌸