Bilal Baraz Bilal Baraz - 2 years ago 112
Javascript Question

How to use variables of data function on VueJS?

I have a stupid problem with VueJS. I'm new with VueJS. I want to access and change variables of data function. However I couldn't do it.

Line which is getting error:

console.log('item: ' + this.item);


Error is here:


TypeError: Cannot read property 'item' of undefined


Here is my code:

data: function(){
return {
item: 69,
file: 0
};
},

methods: {
toggle: (elementId = 0, type = 'item') => {
console.log('element ID: ' + elementId);
console.log('type: ' + type);
console.log('item: ' + this.item);

switch (type) {
case 'item':
break;
case 'file':
break;
}
}
}

Answer Source

Use toggle(elementId = 0, type = 'item') {} instead of toggle: (elementId = 0, type = 'item') => {}.
arrow function assigns this to its parent's this of the scope.
See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Arrow_functions_used_as_methods

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download