在Vue中我们有时候会用到组件间通信,通过$emit绑定事件,然后通过$on触发,那么怎样获取到$on里的数据呢?
比如组件A中,我们想通过$emit向组件B传递this.value值,在组件B中通过$on获取,我们发现在$on事件外部根本无法获取到组件A传来的数据。
// 组件A:
methods:{
sure() {
bus.$emit("blur", this.value);
}
}
// 组件B:
created() {
bus.$on('blur', arg => {
this.time = arg
})
console.log(this.time) // undefined
}
那么究竟应该怎么做才能获取到arg呢,我们可以使用app作为中间件就能获取到:
// 组件B:
created() {
bus.$on('blur', arg => {
app.time = arg
})
console.log(app.time) // 8:30
}