簡體   English   中英

Vue.js從Promise更新模板中的值

[英]vuejs update value in template from a promise

我是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:無法設置未定義的屬性'count'”

在發現

--->

而此錯誤在此this.count = Review.stats(productCode)

TypeError:無法設置未定義的屬性“ count”

您應該在.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);
  },
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM