Vue v-for指定索引插入促销图且不遗漏遍历项的实现方法
v-for循环指定位置插入促销图同时不遗漏列表项的实现方案
问题场景
现有长度为5的产品列表,通过v-for指令做循环渲染,需求为:循环执行到索引值为2(第三次迭代)的位置时,在该位置插入一张促销图片,同时保证所有5个产品都正常渲染,不出现截断、遗漏。
预期渲染结构
<!-- 共渲染5个产品+1张促销图 --> <template v-for="product in collection.products"> <div class="product-item item--1x1">Product 1</div> <div class="product-item item--1x1">Product 2</div> <div class="promotion-image item--2x2"></div> <div class="product-item item--1x1">Product 3</div> <div class="product-item item--1x1">Product 4</div> <div class="product-item item--1x1">Product 5</div> </template>
原有写法的问题
原先的实现用v-if/v-else做二选一渲染,代码如下:
<template v-for="(product, index) in collection.products"> <div v-if="index === 2" class="promotion-image item--2x2"></div> <div v-else class="product-item item--1x1"> </template>
该写法存在两个核心问题:
- 逻辑错误:当索引为2时走
v-if分支只渲染促销图,直接跳过了当前索引对应的产品项,5次循环仅渲染4个产品+1张促销图,自然会丢失最后1个产品 - 语法错误:产品项的
div标签未闭合,会导致渲染结构异常
正确实现代码
不需要用v-else跳过产品渲染,只需要在遍历到索引2时,额外插入促销图即可,所有产品项保持正常渲染:
<template v-for="(product, index) in collection.products" :key="product.id"> <!-- 遍历到索引2时,先在当前位置插入促销图 --> <div v-if="index === 2" class="promotion-image item--2x2"></div> <!-- 所有索引位置都正常渲染当前产品,不做跳过逻辑 --> <div class="product-item item--1x1">{{ product.content }}</div> </template>
逻辑说明
- 循环总次数仍为5次,每次都会渲染对应产品,不会出现产品遗漏
- 仅在索引为2的那次循环中,多渲染1张促销图,最终总节点数为5个产品+1张促销图,和预期结构完全一致
- 记得给
v-for绑定唯一key值,避免Vue虚拟DOM渲染异常
内容的提问来源于stack exchange,提问作者dbzx10299
相关产品推荐
相关产品推荐

