侦听组件 b 中总线的自定义事件。但是,在组件 a 中调度事件后,它访问组件 b。组件b的监听函数执行了,但是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>总线.jsimport 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',但是没有用。你能帮助我吗?如果可能,我想深入了解“巴士”
2 回答
HUH函数
TA贡献1836条经验 获得超4个赞
这仅在您发出时页面中同时存在组件 A 和组件 B 时才有效。从代码来看,您似乎是从组件 A 发出值,然后导航到组件 B 并期望那里的值。
你正在做的事情就像踢一个球,然后追着它跑,然后捡起来却发现球已经消失了。您需要的是已经在该位置的另一个人接球。
这种情况下的解决方案可以是在 localstorage 中设置值,导航到另一条路由,然后从 localstorage 读取值。
如果您需要传递的值是一个简单的值,您可以将它传递到查询字符串中,然后从组件 B 中的 $router params 中读取。
翻翻过去那场雪
TA贡献2065条经验 获得超13个赞
从组件 A 发出事件后,您的代码将无法按预期工作,因为您正在更改路线。因此它无法被组件 B 捕获。
您可以在此处为 mixins或使用 localstorage在混合外观中保存更改的值。您还可以使用先前答案中所述的查询字符串
添加回答
举报
0/150
提交
取消