use $on() in another component

Published 2 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/

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