use $on() in another component

Published 7 months ago by afoysal

I am trying to use checked values of HTML checkboxes in another component like below but I am not getting any output.

data() {
                return {
                    values: [],
                }
            },
            computed: {
                formated () {
                    console.log(this.values)
                }
            },
            created () {
                EventBus.$on('change', function (skillName) {
                    this.values = skillName
                });
            },
bobbybouwmann

You need to use $set('values', skillName) for that.

created () {
    var that = this;
    EventBus.$on('change', function (skillName) {
        that.$set('values', skillName);
    });
},
mankowitz

Supplemental question: Why do you need

var that=this;

Doesn't vue.js automatically create a local this var that will be hoisted into any closures?

bobbybouwmann

@mankowitz Aah yeah of course this should work by default! Sorry about that!

Updated code:

created () {
    EventBus.$on('change', function (skillName) {
        this.$set('values', skillName);
    });
},
afoysal

@bobbybouwmann , I am getting this error.

enter image description here

bobbybouwmann

Show your full code please...

mankowitz

@bobbybouwmann -

(sorry to ask so many questions) What is the benefit of creating another vue instance to be an EventBus? Specifically, why do

EventBus.$on(...)

when you could just do

this.$on(...)
bobbybouwmann

@mankowitz You need a separate vue instance that will run as the EventBus. This instance is shared through all components. You can find more information here: https://alligator.io/vuejs/global-event-bus/

Krunal10

How To Create A Global Event Bus? An event bus is the pub/sub pattern. Means one component publishes an event and another component subscribes to that event. So one component Vue component emits an event with some data, and another component subscribes to that event and receives that data. You need a separate vue instance that will run as the EventBus. This instance is shared through all components. Read more here.. https://appdividend.com/2018/06/03/how-to-create-a-global-event-bus-with-vue-js/

Please sign in or create an account to participate in this conversation.