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

给你一囗甜甜゛ 提交于 2020-12-26 09:11:39

问题


Listen for custom events for the bus in component b. However, after dispatching events in component a, it accesses component b. the listening function of component b is executed, but msg of data function is not updated

Please don't say Vuex.

The relevant code is based on Vue CLi3

Here code: Component 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>

component 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()

router:

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
    }]
})

I tried using 'watch' to observe 'msg', but it didn't work.

Can you help me?

If possible, I would like to deeply understand 'bus'


回答1:


This will work only if both component A and component B are present in the page at the time you are emitting. From the code it seems that you are emitting the value from component A and then navigating to component B and expecting the value there.

What you are doing is something like kicking a ball and then running after it and then picking it only to find that the ball has disappeared. What you need is another person already present at that location who picks up the ball.

A solution in this case can be to set the value in localstorage, navigate to the other route and then read the value from localstorage.

If the value you need to pass is a simple value, you can just pass it in query string and then read from $router params in component B.




回答2:


Your code will not work as expected as your are changing route after emitting event from Component A. So it can't be catch by Component B.

You can save the changed value in mixing look here for mixins or use localstorage. And you can also use query string as stated in previous answer



来源:https://stackoverflow.com/questions/58554365/how-do-you-eventbus-a-bus-to-communicate-updates-to-a-view-in-a-vue-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!