Bilal Baraz
Bilal Baraz

Reputation: 135

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;
        }
    }
}

Upvotes: 0

Views: 79

Answers (1)

choasia
choasia

Reputation: 10852

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

Upvotes: 2

Related Questions