您如何使用 eventBus 总线将更新传达给 Vue 组件中的视图?

How do you eventBus a bus to communicate updates to a view in a Vue component?

监听组件 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>

bus.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 并期望那里的值。

你所做的就像踢一个球,然后 运行 踢球然后捡起来却发现球不见了。你需要的是另一个已经在那个位置接球的人。

这种情况下的解决方案是在 localstorage 中设置值,导航到其他路由,然后从 localstorage 中读取值。

如果你需要传递的值是一个简单的值,你可以在查询字符串中传递它,然后从组件B中的$router params中读取。

您的代码将无法按预期工作,因为您在从组件 A 发出事件后更改路由。因此它无法被组件 B 捕获。

您可以将更改后的值保存在 mixing look here for mixins 中或使用 localstorage。您还可以使用先前答案中所述的查询字符串