gpt4 book ai didi

javascript - 如何修复 Vue 警告 : You may have an infinite update loop in a component render function

转载 作者:行者123 更新时间:2023-12-04 10:21:02 25 4
gpt4 key购买 nike

我收到以下无限循环警告。我知道这可能是因为由于方法调用,我正在更改模板的 for 循环中的变量。知道如何解决吗?循环确实完成了,所以它实际上不是无限循环,但我想修复警告。

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

代码片段:

new Vue({
el: '#app',
data: {
contents: {"34": {"id": 34, build_name: "email_simple", build_readable: "Email"},"35": {"id": 35, build_name: "email_complex", build_readable: "Email"},"36": {"id": 36, build_name: "email_half", build_readable: "Email"}},
last_build_type: '',
contents_tree: [34,35,36]
},
methods: {
checkBuildType(id){
let check = false;
if(this.last_build_type !== this.contents[id].build_name){
check = true
}
this.last_build_type = this.contents[id].build_name;
return check
}

}

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<template v-for="(id, i) in contents_tree">
<div v-bind:key="i + '_' + id" class="inline">
<template v-if="checkBuildType(id)">
{{i}} - {{id}} -
{{contents[id].build_readable}}
<br>

</template>

</div>
</template>
</div>

最佳答案

您收到该警告是因为 Vue 必须为 v-for 循环中的每个项目重新渲染,因为 for 循环会更新组件的状态。我的解决方案是在一个计算属性(基本上是一个索引对象)中一次计算每个数组项的结果,并在 v-for 中访问该计算属性,而不是使用 checkBuildType 方法。

new Vue({
el: '#app',
data: {
contents: {
"33": {
"id": 33,
build_name: "email_half",
build_readable: "Email"
},
"34": {
"id": 34,
build_name: "email_simple",
build_readable: "Email"
},
"35": {
"id": 35,
build_name: "email_complex",
build_readable: "Email"
},
"36": {
"id": 36,
build_name: "email_half",
build_readable: "Email"
},
"37": {
"id": 37,
build_name: "email_half",
build_readable: "Email"
}
},
last_build_type: '',
contents_tree: [34, 35, 36, 37, 33]
},
computed: {
buildTypes() {
const buildTypesMap = {};
for (id of this.contents_tree) {
buildTypesMap[id] = this.checkBuildType(id);
}
return buildTypesMap
}
},
methods: {
checkBuildType(id) {
let check = false;
if (this.last_build_type !== this.contents[id].build_name) {
check = true
}
this.last_build_type = this.contents[id].build_name;
return check
}

}

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<template v-for="(id, i) in contents_tree">
<div v-bind:key="i + '_' + id" class="inline">
<template v-if="buildTypes[id]">
{{i}} - {{id}} -
{{contents[id].build_readable}}
<br>

</template>

</div>
</template>
</div>

关于javascript - 如何修复 Vue 警告 : You may have an infinite update loop in a component render function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60848954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com