Vue嵌套v-for渲染时点击事件仅修改指定行数据如何实现?
实现方案
1. 数据结构调整
给每个父级对象新增currentSubIndex属性,初始值设为0,用来记录当前选中的子元素索引,刚好满足初始展示子数组第一个元素的要求:
infos: [{ name: 'name1', currentSubIndex: 0, infosName: [{ place: 'place.1.1', surface: '100' }, { place: 'place.1.2', surface: '200' } ] }, { name: 'name2', currentSubIndex: 0, infosName: [{ place: 'place.2.1', surface: '300' }, { place: 'place.2.2', surface: '400' } ] } ]
如果是Vue2项目,初始化时没有提前声明currentSubIndex字段,需要用$set新增响应式属性:
// 初始化数据时批量添加响应式字段 this.infos.forEach(item => { this.$set(item, 'currentSubIndex', 0) })
2. 模板渲染
外层v-for遍历父级数组,直接通过currentSubIndex取对应子元素渲染即可,不需要嵌套v-for渲染全部子元素:
<template> <div> <div v-for="(item, parentIndex) in infos" :key="parentIndex" class="row" > <span>父级名称:{{ item.name }}</span> <span>位置:{{ item.infosName[item.currentSubIndex].place }}</span> <span>面积:{{ item.infosName[item.currentSubIndex].surface }}</span> <!-- 点击切换按钮,传入父索引和目标子索引即可 --> <button @click="changeSubItem(parentIndex, 0)">展示第一个子项</button> <button @click="changeSubItem(parentIndex, 1)">展示第二个子项</button> </div> </div> </template>
3. 点击事件处理
接收父索引和目标子索引两个入参,直接修改对应父项的currentSubIndex即可,只会触发当前行的视图更新,不会影响其他行:
methods: { changeSubItem(parentIndex, targetSubIndex) { this.infos[parentIndex].currentSubIndex = targetSubIndex // Vue2未提前声明字段时用下方写法: // this.$set(this.infos[parentIndex], 'currentSubIndex', targetSubIndex) } }
内容的提问来源于stack exchange,提问作者Marwan Tagragant
相关产品推荐
相关产品推荐

