Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vue.js - Vue warn]: You may have an infinite update loop in a component render function

Getting an infinite loop error when looping through <a> attributes in vue.js. I have a method that loops through and adds attributes dynamically but when I use the method by binding it to an attribute in the <a> I get the error from the title. The attributes are a nested object within the original products array of objects.

Vue Code

<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>
question from:https://stackoverflow.com/questions/65909636/vue-warn-you-may-have-an-infinite-update-loop-in-a-component-render-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You use a method call to pass its result to additionalAttrs prop but it's not reactive and potentially can be called as many times as you have elements in products array

You just need one computed prop instead of an array and a method because they simply depend on 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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...