Reputation: 2178
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.
Upvotes: 4
Views: 3288
Reputation: 39466
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() {
// ...
}
});
Upvotes: 5
Reputation: 2178
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
Upvotes: 0