【发布时间】:2021-03-21 13:08:03
【问题描述】:
我是一名计算机科学专业的新生,我有一个关于 Vue.js 的学校项目要做。 它正在工作,但它显示以下警告:
[Vue 警告]:组件渲染函数中可能存在无限更新循环。
英语不是我的第一语言,所以如果我提前写错了,我很抱歉,但我会尽力解释我在项目上要做的事情。
我必须创建一个照片网格/相册,每行显示不超过 3 张照片。像这样的东西: Example of how it has to look
代码是这样的:
<template>
<v-container>
<!-- 'v-container' est´substituindo ' div class="clubes-lista" '-->
<div class="grid-photo">
<v-container class="grey lighten-3">
<v-row
v-for="index in numberLines()"
:key="index"
class="grey lighten-3"
>
<v-col v-for="n in 3" :key="n" cols="4">
<v-card v-if="numberPhotos > checkInsertedAllPhotos()" outlined>
<v-img
src="https://i.pinimg.com/736x/96/28/b7/9628b7892fd0543782f53eeec4bae502.jpg"
alt="Bird Photo"
>
</v-img>
<div class="photo-subtitle">
<v-icon size="15">mdi-heart-outline</v-icon>
<p>The Cockatiel</p>
</div>
</v-card>
<v-card v-else></v-card>
</v-col>
</v-row>
</v-container>
</div>
</v-container>
<script>
export default {
name: "PhotoGrid",
data() {
return {
listPhotosOnGrid: [],
numberPhotos: 0,
numberTotalLines: 0,
countPhotos: 0,
};
},
computed: {},
methods: {
createPhotosList() {
var listPhotos = [];
for (var i = 0; i < 10; i++) {
var aux = {
id: i + 1,
src:
"https://i.pinimg.com/736x/96/28/b7/9628b7892fd0543782f53eeec4bae502.jpg",
subtitle: "The cockatiel",
};
listPhotos.push(aux);
}
this.listPhotosOnGrid = listPhotos;
this.numberPhotos = listPhotos.length;
},
numberLines() {
this.createPhotosList();
var photosMultipleThree = this.numberPhotos;
while (photosMultipleThree % 3 != 0) {
photosMultipleThree = photosMultipleThree + 1;
}
this.numberTotalLines = photosMultipleThree / 3;
return photosMultipleThree / 3;
},
checkInsertedAllPhotos() {
var cont = this.countPhotos++;
return cont;
},
},
};
<style scoped>
.photo-subtitle {
font-size: 10px;
display: flex;
flex-direction: row;
justify-content: left;
align-items: flex-start;
padding: 0;
margin-top: 10px;
}
.photo-subtitle p {
margin-left: 5px;
}
所以...试图弄清楚发生了什么,我认为警告来自以下行:
<v-card v-if="numberPhotos > checkInsertedAllPhotos()" outlined>
if 是因为它不能显示比给出的更多的图像。例如,每行显示 3 张照片,所以如果我没有多张 os 3 的照片,我不想填充最后一行的所有列,只显示所有照片所必需的。
但我只是认为,根据一些测试,我不确定警告是否来自这一行。
代码有效,但我觉得有些不对劲。 (它实际上是部分工作的,因为我仍然不知道如何从数组中获取要显示的信息,所以它只循环相同的东西)
我想学习如何做对。
那么谁能告诉我我可以做些什么来使警告消失,或者我是否必须更改所有内容,并创建一个新的逻辑以使其正常工作。
我只是想学习。
非常感谢,如果这是一个愚蠢的问题,或者如果我把一切都弄错了,再次抱歉,呵呵。 如果我写错了,请见谅。
:)
【问题讨论】:
-
首先,1.这个函数
checkInsertedAllPhotos()总是返回1,因为你只增加1一次。 2.v-for="index in numberLines()"这里的numberLines()是一个数字,因为你返回photosMultipleThree / 3。你不能循环一个数字。 -
3.不建议在 v-for 中使用 v-if。相反,先使用计算属性过滤数组,然后循环过滤数组
标签: vue.js vuejs2 vue-component vuetify.js