0

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;
        }
    }
}
5
  • console.log('item: ' + this.item); this is not an error Commented Aug 16, 2017 at 9:56
  • Share the error message too. Commented Aug 16, 2017 at 9:56
  • Ok guys, Post was updated as you wish. Commented Aug 16, 2017 at 9:59
  • Try this.$data.item to access the data. Commented Aug 16, 2017 at 10:04
  • @ThomasKleßen unfortunately, got the same error for $data Commented Aug 16, 2017 at 10:10

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.