监听组件 b 中总线的自定义事件。然而,在组件a中分派(dispatch)事件后,它访问组件b。组件b的监听函数被执行,但是data函数的msg
没有更新
请不要说Vuex。
相关代码基于Vue CLi3
这里的代码: 组件A:
<template>
<div>
Component A
<button @click="sendMsg">pushB</button>
</div>
</template>
<script>
import bus from './bus'
export default {
methods: {
sendMsg() {
bus.$emit('send', 'hello Component B')
this.$router.push('/bbb')
}
}
}
</script>
B组份:
<template>
<div>
<p>component B:{{ msg }}</p>
</div>
</template>
<script type="text/javascript">
import bus from './bus'
export default {
data () {
return {
msg: 'bbb'
}
},
mounted () {
bus.$on('send', data => {
console.log(data)
console.log(this)
this.msg = data
})
}
}
</script>
总线.js
import Vue from 'vue';
export default new Vue()
路由器:
const aaa = () => import('@/components/demo/bus/a')
const bbb = () => import('@/components/demo/bus/b')
export default new Router({
routes: [{
path: '/aaa',
component: aaa
},
{
path: '/bbb',
component: bbb
}]
})
我尝试使用“watch”来观察“msg”,但没有成功。
你能帮我吗?
如果可以的话,我想深入了解‘bus’
最佳答案
仅当您发出时页面中存在组件 A 和组件 B 时,此方法才有效。从代码来看,您似乎正在从组件 A 发出值,然后导航到组件 B 并期望那里的值。
你所做的就像踢一个球,然后追它,然后捡起它,却发现球已经消失了。您需要的是另一个已经在场在该位置的人来 catch 。
这种情况下的解决方案可以是在本地存储中设置值,导航到其他路由,然后从本地存储中读取值。
如果您需要传递的值是一个简单的值,您可以将其传递到查询字符串中,然后从组件 B 中的 $router params 中读取。
关于javascript - 如何使用 eventBus 作为总线来将更新传递给 Vue 组件中的 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58554365/