Vue.js条件渲染与v-for未按预期工作的问题解决
问题分析与解决方案
核心问题
splice()修改原数组:splice(0,4)会直接删除photos数组的前4个元素,导致组件每次渲染时数组长度骤减,最终变为0,永远触发checkCount === 1的条件。v-if条件错误:模板中(checkCount = 1)是赋值操作,不是相等判断,应该使用===。- 计算属性逻辑依赖被修改的数组:
checkCount基于photos长度判断,但photos被模板里的splice修改,导致逻辑完全混乱。
解决步骤
- 替换
splice()为slice():slice(0,4)返回原数组前4个元素的副本,不会修改原数组;通过计算属性提前把数组按每组4个拆分,避免模板中直接操作数组。 - 修正
v-if的判断符号:将赋值=改为全等判断===。 - 预处理数组分组:用计算属性拆分数组,让逻辑更清晰,避免重复计算。
修改后的完整代码
模板部分
<div v-if="checkCount === 1"> <Splide :options="{ rewind: true }" aria-label="Carousel Pictures"> <SplideSlide class="fs-800"> <div v-for="item in photoGroups[0]" :key="item.text"> <a href=""> <img :src="item.img" alt="" /> <p>{{ item.text }}</p> </a> </div> </SplideSlide> </Splide> </div> <div v-else-if="checkCount === 2"> <Splide :options="{ rewind: true }" aria-label="Carousel Pictures"> <SplideSlide class="fs-800" v-for="(group, index) in photoGroups" :key="index"> <div v-for="item in group" :key="item.text"> <a href=""> <img :src="item.img" alt="" /> <p>{{ item.text }}</p> </a> </div> </SplideSlide> </Splide> </div>
脚本部分
data() { return { photos: [ { img: "https://picsum.photos/300/300", text: 1 }, { img: "https://picsum.photos/300/300", text: 2 }, { img: "https://picsum.photos/300/300", text: 3 }, { img: "https://picsum.photos/300/300", text: 4 }, { img: "https://picsum.photos/300/300", text: 5 }, { img: "https://picsum.photos/300/300", text: 6 }, { img: "https://picsum.photos/300/300", text: 7 }, { img: "https://picsum.photos/300/300", text: 8 }, ], }; }, computed: { photoGroups() { // 按每组4个拆分photos数组 const groups = []; for (let i = 0; i < this.photos.length; i += 4) { groups.push(this.photos.slice(i, i + 4)); } return groups; }, checkCount() { const len = this.photos.length; if (len <= 4) { return 1; } else if (len > 4 && len <= 8) { // 修正原逻辑漏洞,覆盖5-8个元素的情况 return 2; } else if (len > 8 && len <= 12) { // 修正原逻辑漏洞,覆盖9-12个元素的情况 return 3; } else { return 4; } }, },
额外说明
原checkCount逻辑存在漏洞:比如5个元素时,len>5不成立会走到else返回4,调整后len>4 && len<=8能正确覆盖5-8个元素的场景,符合预期逻辑。
内容的提问来源于stack exchange,提问作者Thomas Rafael Cruz
相关产品推荐
相关产品推荐

