vue.js - 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>
解决方案
您使用方法调用将其结果传递给additionalAttrs
prop,但它不是响应式的,并且可能会被调用多次,因为您在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
}
}
推荐阅读
- django - 我的表单没有保存使用引导程序在 django 中进行样式设置
- reactjs - 来自 useSelector 的数据导致无限重新渲染为依赖项
- python - 有没有办法在 O(1) 时间复杂度中删除 Python 中字符串的最后一个字符?
- r - 在 R 中对列名使用 mutate
- python - 具有多个键的熊猫数据框到 json
- twilio - WhatsAPP - 通过 Twilio 集成 MS Teams
- neural-network - 如何修复 pytorch 神经网络中不正确的通道大小?
- nginx - 让我们加密,而不是将一个 URL 重定向到 https
- python - 无法使用 Beautifulsoup 从 span 获取文本
- react-native - 为什么这个 reducer 不更新状态?