4

I'm having issues with initialising my Vue component with data from localStorage. Here is a simplified version of my code

new Vue({
    el: "#my-element",
    created: () => {
        if (window.localStorage.getItem("verified")) {
            this.verification.verified = true;
        }
    },
    data: {
        verification: {
            verified: false
        }
    }
});

But I keep getting an error on the console Cannot read property 'verification' of undefined

If I put a debugger in the created() function, and I check the values of this, this.verification and this.verification.verified, they're all set to the values I have initialized with in the data object.

Can someone explain what I am doing wrong?

Basically I'm trying to hide an element when the page loads if the user has already gone through the verified process at any previous time.

2 Answers 2

5

The arrow function is intended for use when you want the value of this in the outer context to flow into your function body, rather than the function having its own context for this. This means that this in your created function does not point to your Vue instance.

You can however still use the shorthand method declaration syntax provided by ES6:

new Vue({
    created() {
        // ...
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

Okay I figured out the problem.. It's because I'm using ES2015 notation for functions.. Changing back to function(){} allows it to work again.. So I need to do some more research to figure out how to use ES2015 with Vue.js

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.