VUE不同页面间的传值之EventBus传递的值不显示
EventBus称为事件总线。
EventBus就如同公交车,通过’$emit’让乘客(即所要传递的值)在发出地上车,在目的地通过’$on’使乘客下车。
1.初始化
方法1
首先需要创建EventBus.js并将其导出,以便其它模块可以使用或者监听它。
import Vue from 'vue'
export const EventBus = new Vue()
方法2
直接在main.js文件中加入
Vue.prototype.$EventBus = new Vue()
注:法2未使用过
2.发送事件
home页面
<template>
<div class="home">
home
<h2>这是在home中本身的data数据:{{ name }}</h2>
<button @click="fire()">点击发射</button>
</div>
</template>
<script>
import { EventBus } from "./eventbus.js";
export default {
name: "Home",
components: {},
data() {
return {
name: "张三",
};
},
methods: {
fire() {
//在$emit中第一个参数为自定义事件名,第二个参数为要传递的值
EventBus.$emit("fireName", this.name);
console.log(this.name);
},
},
};
</script>
3.接收事件
about页面
<template>
<div class="about">
<h1>This is an about page</h1>
<h2>这是home发射过来的name:{{ newname }}</h2>
</div>
</template>
<script>
import { EventBus } from "./eventbus.js";
export default {
name: "About",
data() {
return {
newname: "李四",
};
},
created() {
//注意此处的值第一个参数要与发出组件中$emit的第一个参数相同
EventBus.$on("fireName", (message) => {
this.newname = message;
});
},
};
</script>
当点击按钮后有两种情况,如果你两个组件在同一页面,李四变张三。不在同一页面,李四未变成张三。
但是可以获取到name的值,就是传不到about页面中。
最先开始以为是页面刷新,将数据也刷新了,没有传递过来。然后用了keep-alive,结果然并卵。只能百度,了解到与组件的生命周期有关。
新组件:beforeCreate
↓
新组件:created
↓
新组件:beforeMount
↓
旧组件:beforeDestroy
↓
旧组件:destroyed
↓
新组件:mounted
由此可以了解到你要在新组件dom挂载前将值传出来。
即你要在home页面中添加,二者选其一
// destroyed() {
// this.fire();
// },
beforeDestroy () {
this.fire();
}
在about页面中添加,二者选其一,只要别在挂载完成后执行就可以了
// beforeMount () {
// EventBus.$on("fireName", (message) => {
// this.newname = message;
// });
// },
created () {
EventBus.$on("fireName", (message) => {
this.newname = message;
});
}
最终结果显现:张三来到了about页面