【问题标题】:referring to a v-for element from inside a getter of computed function从计算函数的 getter 中引用 v-for 元素
【发布时间】:2019-03-26 04:19:53
【问题描述】:

在 Vue 中,我有一个 v-for 循环,它根据我拥有的对象呈现输入。 输入是一个 v-model 到一个计算函数:

<template v-for="product in products>"
  {{ product.Name }}: <input type="text" v-model="productAmount">
</template>

因此,带有 get 和 setter 的计算函数:

computed: {
  productAmount: {
    get () {
      this.product.DefaultAmount
    },
    set (newAmount) {
      // doing something
    }
  }
}

问题是get() 中的this.product 未定义。

有没有办法在计算函数的getter中引用v-for的动态变量?

【问题讨论】:

标签: javascript vuejs2 v-for


【解决方案1】:

如果您想使用 computed 属性,您应该创建一个子组件并将产品作为属性传递 (&lt;Procuct v-for="p in products" :product="p"/&gt;)。

或者,如果它不是一项昂贵的操作,您可以轻松地将 computed 替换为 method 并使用它:

...
methods: {
  getAmountForProduct(product) {
    return product.DefaultAmount
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2022-01-01
    • 2021-06-18
    • 2018-10-31
    • 2019-05-30
    • 2021-12-07
    相关资源
    最近更新 更多