【问题标题】:Vue warn]: You may have an infinite update loop in a component render functionVue warn]:组件渲染函数中可能存在无限更新循环
【发布时间】:2021-04-30 17:25:51
【问题描述】:

循环通过 vue.js 中的 <a> 属性时出现无限循环错误。 我有一个循环并动态添加属性的方法,但是当我通过将其绑定到<a> 中的属性来使用该方法时,我从标题中得到了错误。属性是原始 products 对象数组中的嵌套对象。

Vue 代码

<template>
  <div>
    <p>
      <a
        v-for="product in products"
        :href="product.product_url"
        type="submit"
        v-bind:additionalAttrs="addAttributes()"
      >
        Click Me
      </a>
    </p>
  </div>
</template>

<script>
export default {
data () {
    return {
      addedAttributes: [],
    };
  },
props: {
    products: Array,
  },
methods: {
    addAttributes() {
      this.products.forEach(product => {
          for (const [key, value] of Object.entries(product.attributes)) {
            this.addedAttributes.push(`${key}: ${value}`);
        }
      });
    }
  }
}
</script>

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    您使用方法调用将其结果传递给 additionalAttrs 道具,但它不是反应式的,并且可能会被调用多次,因为您在 products 数组中拥有元素

    你只需要一个计算的 prop 而不是一个数组和一个方法,因为它们只依赖于 products prop:

    <a
      v-for="product in products"
      :href="product.product_url"
      type="submit"
      v-bind:additionalAttrs="addedAttributes"
    >
    Click Me
    </a>
    
    computed: {
      addedAttributes() {
          const addedAttributes = []
          this.products.forEach(product => {
              for (const [key, value] of Object.entries(product.attributes)) {
                addedAttributes.push(`${key}: ${value}`);
            }
          });
          return addedAttributes
        }
    }
    

    【讨论】:

    • 是的,这就是问题所在,很高兴知道如果我只依赖传入的道具,我就可以使用计算的 vs 方法。
    • 如果你希望它是反应式的
    猜你喜欢
    • 2018-05-03
    • 2020-04-30
    • 2019-02-12
    • 2019-02-07
    • 2017-08-26
    • 2021-03-21
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多