首页 > 解决方案 > Vue warn]:组件渲染函数中可能存在无限更新循环

问题描述

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

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

解决方案


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

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

<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
    }
}

推荐阅读