在el-table-column的template中使用v-if来判断编辑标志位导致编辑输入框显示串行的问题

文章描述了一个在Vue.js项目中,表格单元格编辑功能出现的问题。原本的设计是通过在每一行数据对象中添加一个编辑标志位来控制输入框的显示和隐藏,但当数据量增加后,点击修改会导致输入框串行显示。问题出在使用v-if和v-for时,编辑标志位没有正确地与表格数据同步。解决方案是将编辑标志位保存在数据列表中,并通过当前行的索引来控制编辑状态,从而解决了不同行之间的状态干扰问题。
摘要由CSDN通过智能技术生成

在项目中有一个需求是表格中有一列的数据可以点击修改,但是不能使用弹窗,需要在点击修改按钮时单元格内容变为输入框进行编辑,点击保存隐藏输入框,显示数据。

在一开始我的思路是在每行的对象中设置一个Boolean类型的标志位,在template标签中使用v-if来判断编辑状态,进而实现展示隐藏输入框,只有一行数据时测试没有问题,当数据量多了以后发现每次点击修改按钮,显示的输入框会串行显示,如下图:
在这里插入图片描述
这是原来错误的代码:

<el-table-column align="center" label="分数" width="100" :resizable="false" >
    <template slot-scope="scope">
        <div>
            <el-form  v-if="scope.row.editScoreFlag" :model="editScoreForm" ref="scoreForm" :rules="rules">
                <el-form-item prop="score">
                    <el-input v-model="editScoreForm.score"></el-input>
                </el-form-item>
            </el-form>
            <p v-else :class="scope.row.score<60 ? 'score-text':''" >{{ scope.row.score }}</p>
        </div>
    </template>
</el-table-column>
editScore(row, index) {
    this.editScoreForm = {
        courseId: this.$route.query.courseId,
        id: row.id,
        score: row.score
    };
    this.$set(this.studentScoreList[index], 'editScoreFlag', true);
},

问题出现在 v-if=“scope.row.editScoreFlag” 这一行上。因为 editScoreFlag 控制着是否显示 el-form 输入框,而这个值是保存在 scope.row 中的,而 scope.row 是由 v-for 渲染得来的,它们之间存在关联。由于editScoreFlag是行内没有的属性,我在点击修改时强行加进去的,在$data中没有定义,在 v-if 判断时,由于 v-for 会生成多个相同的 元素,当点击修改时,editScoreFlag 的值会改变,但由于该值并没有保存到对应的表格展示数据 studentScoreList 中,所以所有表格中的元素都发生了变化。

解决该问题有两种方法

  1. 需要把 editScoreFlag 作为studentScoreList 中的一个数据来保存,这样每个 元素中保存的都是当前列的状态,不会互相干扰。
  2. 将 v-if=“scope.row.editScoreFlag” 修改为 v-if=“scope.$index === rowEditIndex”, rowEditIndex 为当前列的索引,并将它保存在 $data 中。
    下面的修改采用第二种方式:
 <el-table-column align="center" label="分数" width="100" :resizable="false" >
    <template slot-scope="scope">
        <div>
            <el-form  v-if="scope.$index==editIndex" :model="editScoreForm" ref="scoreForm" :rules="rules">
                <el-form-item prop="score">
                    <el-input v-model="editScoreForm.score"></el-input>
                </el-form-item>
            </el-form>
            <p v-else :class="scope.row.score<60 ? 'score-text':''" >{{ scope.row.score }}</p>
        </div>
    </template>
</el-table-column>
export default {
	data() {
		return {
			editIndex: -1,
		}
	},
	methods: {
		editScore(row, index) {
            this.editScoreForm = {
                courseId: this.$route.query.courseId,
                id: row.id,
                score: row.score
            };
            this.editIndex=index;
        },
	}
}

这样就可以解决上述问题了

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值