vuejs从promise中更新模板中的值

时间:2017-05-16 10:00:56

标签: javascript vue.js

我是VueJS的新手,发现缺少文档,但我正在尝试处理一个组件,它设置一个默认值,将注释计数为0,但是当一个promise返回一个值时,我想在图。

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

我不确定我做错了什么,但这给了我以下错误,过去一小时我一直在做错。

  

[Vue警告]:创建的钩子出错:“TypeError:无法设置属性   '计数'未定义“

     

中找到      

---&GT;          

此错误位于this.count = Review.stats(productCode)

  

TypeError:无法设置未定义的属性'count'

1 个答案:

答案 0 :(得分:2)

您应该在.then回调中设置值。也不要将箭头函数用于created(以及其他方法),否则您将丢失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);
  },
});