Reputation:
I'm new to VueJS and find the documentation lacking but I'm trying to work on a component where it sets a default value to comment count to 0 but then when a promise returns a value I want to update this in the view.
Vue.component('commentsCount', {
template: `
<strong class="t-bold">{{count}}</strong>
`,
data: () => ({ count: 0 }),
created: () => {
this.count = Review.stats(productCode)
.then((res) => {
console.log(res.count);
return res.count;
});
console.log(this);
},
});
I'm not sure what I'm doing wrong but this gives me the following errors and I've been on it for the past hour.
[Vue warn]: Error in created hook: "TypeError: Cannot set property 'count' of undefined"
found in
--->
and this error which is on the line this.count = Review.stats(productCode)
TypeError: Cannot set property 'count' of undefined
Upvotes: 2
Views: 1502
Reputation: 15914
You should set the value in the .then
callback. Also don't use arrow functions to created
(and other methods), or you will lost the context of this
. Try this:
Vue.component('commentsCount', {
template: `
<strong class="t-bold">{{count}}</strong>
`,
data: () => ({ count: 0 }),
created () { // can't be an arrow function
Review.stats(productCode)
.then((res) => {
console.log(res.count);
this.count = res.count; // set count here
});
console.log(this);
},
});
Upvotes: 2