首页 > 语言 > JavaScript > 正文

vue+element-ui实现表格编辑的三种实现方式

2024-05-06 15:28:19
字体:
来源:转载
供稿:网友

1、表格内部显示和编辑切换

这种方式就是利用两个标签显示隐藏来实现,我们这里用input和span,正常用span将数据显示,点击编辑时,将span隐藏,显示input进行编辑。选中当前行我们可以通过slot-scope中的index去实现,在控制显示隐藏的属性上绑定index就可以选中当前行了,如showEdit[index]。

页面结构代码:

<el-table :data="tableData" tooltip-effect="dark" style="width: 100%" header-align="center"> <el-table-column width="50" header-align="center">  <template slot-scope="{row,$index}">   <span>{{$index + 1}}</span>  </template> </el-table-column> <el-table-column label="名称" prop="Name" width="300" header-align="center">  <template slot-scope="{row,$index}">   <input class="edit-cell" v-if="showEdit[$index]" v-model="row.Name">   <span v-if="!showEdit[$index]">{{row.Name}}</span>  </template> </el-table-column> <el-table-column  fixed="right"  label="操作"  width="100"  header-align="center">  <template slot-scope="{row,$index}">   <el-button type="text" size="small"  @click.native="handleUpdate($index, row)"  v-if="showBtn[$index]">更新</el-button>   <el-button type="text" size="small"  @click.native="handleCancel($index, row)"  v-if="showBtn[$index]">取消</el-button>   <el-button type="text" size="small"  @click.native="handleEdit($index, row)"  v-if="!showBtn[$index]">编辑</el-button>   <el-button type="text" size="small"  @click.native="handleDelete($index, row)"  v-if="!showBtn[$index]">删除</el-button>  </template> </el-table-column></el-table>

初始化data:

data() { return {  showEdit: [], //显示编辑框  showBtn: [],  showBtnOrdinary: true }}

实现方法:

//点击编辑handleEdit(index, row) { this.showEdit[index] = true; this.showBtn[index] = true; this.$set(this.showEdit,row,true) this.$set(this.showBtn,row,true)},//取消编辑handelCancel(index, row) { this.getContentList(); this.showEdit[index] = false; this.showBtn[index] = false;   },//点击更新handleUpdate(formName) {},//点击删除handleDelete(index, row) {},

初始化的时候最好给数组遍历赋值

for(var i = 0; i < 100; i ++) { this.showEdit[i] = false; this.showBtn[i] = false; this.$set(vm.showEdit[i], false); this.$set(vm.showBtn[i], false);}

另外还可以给row自身添加一个属性,通过row.showEdit来控制每一行的编辑。上面说的这些在我的开发环境实现一点问题都没有,但是测试出来了很多bug(没反应、点击第一次第二次没反应等),后来又查询了一下vue的官方文档“异步队列更新”,可能需要加一个Vue.nextTick(callback)。项目比较紧换了另外一种实现方式。有兴趣的小伙伴可以看看官方文档:https://cn.vuejs.org/v2/guide/reactivity.html

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选