2

I am trying to long time Vue $emit and $on functionality but still I am not getting any solution. I created simple message passing page its two pages only. One is Component Sender and Component Receiver and added eventbus for $emit and $on functionality.

I declared $emit and $on functionality but I don't know where I made a mistake.

please help some one.

Component Sender:

    <script>
    import { EventBus } from '../main';
    export default {
        name: 'Send',
        data () {
            return {
                text: '',
                receiveText: ''
            }
        },

        methods: {
            sender() {
                 EventBus.$emit('message', this.text);
                 this.$router.push('/receive');
            }
        }
    }
    </script>

Component Receiver:

    <script>
    import { EventBus } from '../main';
    export default {
        name: 'Receive',
        props: ["message"],
        data () {
            return {
                list: null
            }
        },
        created() {
            EventBus.$on('message', this.Receive);

        },
        methods: {
            Receive(text){
                console.log('text', text);
                this.list = text;
            },
            save() {
                alert('list', this.list);//need to list value but $emit is not working here

            }
        }
    }
    </script>

Router View:

    const router = new Router({
        mode: 'history',
        routes: [
            {
                path: "/",
                name: "Send",
                component: Send
            },
            {
                path: "/receive",
                name: "Receive",
                component: Receive,
                props: true
            }
        ]
    })

Main.JS

    import Vue from 'vue'
    import App from './App.vue'
    import router from './router';

    export const EventBus = new Vue();

    new Vue({
      el: '#app',
      router,
      render: h => h(App)
    })
T. Short
  • 3,481
  • 14
  • 30
Ananth
  • 65
  • 3
  • 10

2 Answers2

1

The EventBus is designed to allow communication between two components that exist on the page at the same time. If you need data that persists between router-views, then you should look at using a Vuex store.

As it is, the Receiver component doesn't exist at the time of the message being sent, and therefore it has no listener attached to the event.

floodlitworld
  • 583
  • 4
  • 11
1

Well your mistake is here:

created() {
       EventBus.$on('message', this.Receive);
    },

the second argument is an handler it should look like this:

created() {
        EventBus.$on('message', function(data){
           this.Receive(data);
           console.log(data)
        });

    },

you should see now 2 console.log() messages

bill.gates
  • 14,145
  • 3
  • 19
  • 47