el-table当前行的获取和设置,用于表格行操作
1、在vue的data区声明当前行变量对象,如果当前行的信息用于了按钮的状态则需要赋予默认值,否则会报找不到属性的错误,比如下面会用到当前记录的status属性值控制按钮是否可用。
//表格选中的行 data() { return { currentRow:{status:'0'}, } }
2、在methods方法列表中声明表格活动行变更的方法,并绑定表格的current-change事件
//当前行变更时 handleCurrentChange: function(val){ this.currentRow = val !== null ? val:{status:'0'}; }, //绑定事件 <el-table ref="myTable" @current-change="handleCurrentChange">
3、表格查询刷新数据的事件中对当前行进行变量赋值
searchData: function() { //获取数据前赋默认值 this.currentRow = {status:'0'}; drugs.apiGetAllData(queryParam) .then(response => { // 一些逻辑代码 this.listData = response.data.list; //赋值当前行变量,并让表格默认选中第一条数据 if (this.listData.length > 0 ) { this.$refs.myTable.setCurrentRow(this.listData[0]); this.currentRow = this.listData[0]; } }) .catch(error => { this.$message.error('查询失败!失败原因:' + error.response.data.message); }); },
4、声明一个是否有当前活动行的判断函数,在表格行操作按钮点击的时候,进行判断并执行响应的业务逻辑
//当前选择行是否为空 isEmptyRow: function(){ if (this.currentRow == null || this.currentRow.id == null){ this.$message.warning('请先选中要操作的记录行!'); return true; } }, //按钮事件 <sun-button type="primary" @click="rowEdit" hint="修改记录">编辑</sun-button> //编辑操作业务代码 rowEdit: function (){ //判断当前行信息 if (this.isEmptyRow()){ return; } //做一些逻辑处理 }).catch(err => { this.$message.error('编辑失败!<br>' + err.response.data.message); }) },
凡哥,别他妈吹牛逼了