javascriptvuejs2event-handlingvue-cli-3event-bus

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


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'


Solution

  • 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.