Vue开发中如何获取v-for渲染的HTML元素对应的数组索引
方法1:直接通过v-for内置索引参数获取
Vue的v-for遍历数组时支持第二个入参,直接返回当前项对应的数组下标,修改代码如下:
模板部分调整
<!-- 增加index参数接收下标 --> <div v-for="(newContent, index) in temp" :key="newContent.id" @click="showId(index)" v-show="true"> <!-- 动态显示人员序号 --> <h4 class="person" style="margin-left: 0.95vw">Person {{ index + 1 }}</h4> <testmodul1></testmodul1> <div class="trash"> <!-- 点击删除按钮时增加.stop阻止事件冒泡,避免触发父div的点击事件,直接传当前下标 --> <button class="btn btn-outline-danger" @click.stop="deletePerson(index)">Person löschen</button> </div> <hr /> </div>
逻辑部分调整
showId(index){ alert("当前项数组下标为:" + index); }, // 新增删除方法,直接根据下标删除数组对应项 deletePerson(index) { this.temp.splice(index, 1) }
方法2:通过id匹配查找下标
如果不想直接使用索引,可以通过传入的id反向查找对应下标,需要先保证每个temp数组项的id唯一。
你提供的console日志中出现了多个id为0的项,说明你的useIt方法自增逻辑可能存在问题,检查是否正确写为this.id += 1,避免id重复导致匹配错误。
代码实现
showId(id){ // 匹配id相同的项的下标 const index = this.temp.findIndex(item => item.id === id) alert(index); }
内容的提问来源于stack exchange,提问作者FloHawafoena
相关产品推荐
相关产品推荐

