Nausik Nausik - 26 days ago 8
Javascript Question

Access component data in Created or Mounted hook

I'm writing a component for Vue.js and I need to modify data on event. But for some reason, when I access it, it's set as undefined

module.exports = {
data: function() {
return {
visible: true
}
},
mounted: function() {
this.eventHub.$on('minimize', function(window_id) {
console.log(this.visible);
this.visible = !this.visible;
});
},
props: ["windowId"]
}


When the event is called for the first time, data.visible is undefined, for some reason.

Is there anything I'm doing wrong?

Thanks!

Answer Source

Because function (window_id) has it's own scope, you can not access this.

This can be solved by adding self = this.

 let self = this
 this.eventHub.$on('minimize', function(window_id) {
    console.log(self.visible);
    self.visible = !self.visible;
 });

As Nick Rucci pointed out, you can also use an arrow function, and get rid of self = this.

this.eventHub.$on('minimize', (window_id) => {
    console.log(this.visible);
    this.visible = !this.visible;
});