【问题标题】:Nuxt Computed property "itemCost" was assigned to but it has no setterNuxt 计算属性“itemCost”已分配给但它没有设置器
【发布时间】:2020-11-07 14:09:09
【问题描述】:

我有这样的方法:

methods: {
  itemCost(item) {
   let total = 0;

   for(let choice of item.choices) {
     if(choice.cost) total += choice.cost;
   }

   return total
  }
}

而我的 vue 文件是这样的:

index.vue
<div class="container">
  <div class="item" v-for="item in cart.items">
   {{itemCost(item)}}
  </div>
</div>

效果很好,但是我收到了这个我不明白的警告:

Computed property "itemCost" was assigned to but it has no setter.

这是一种方法,而不是计算属性,所以不知道为什么我会收到警告。

我查看了与此类似的问题,但所有答案都提到这是因为它是一个 v-model,所以它需要一个 setter,在这种情况下,我正在尝试输出计算,因此不需要用户输入。

任何想法如何摆脱警告?

【问题讨论】:

  • 能否提供完整的组件代码
  • 看起来你有一个名为itemCost的计算属性?
  • @yash 这是我没有任何计算属性的奇怪之处,它是一种方法而不是计算
  • :0 如果它是真的真的很奇怪。你确定你从上面的代码中得到了错误?
  • @Jordash 你能在 Codesandbox 或 Codepen 中创建一个重现吗?

标签: vue.js nuxt.js


【解决方案1】:

这是因为您的组件结构怪异。您应该在计算之前进行计算,然后使用它打印出来:

computed: {
  itemsWithCost: function() {

    return this.cart.items.map( item => {

      let total = 0;
      for(let choice of item.choices) {
        if(choice.cost) total += choice.cost;
       }
      item.total = total;
      return item;
      }
   })
}

在您的模板中:

index.vue
<div class="container">
  <div class="item" 
     v-for="(item,index) in itemsWithCost" 
    :key="index">
     {{item.total}}
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2018-09-26
    • 2019-05-21
    • 2020-10-23
    • 2020-10-04
    • 2018-11-02
    • 2019-02-16
    • 2018-02-16
    • 2019-08-01
    • 2020-07-09
    相关资源
    最近更新 更多