一、图1:界面效果
说明:
1)删除:触发函数deleteRow
删除当前行。
2)编辑:触发函数editRow
将当前行激活,界面发生变化。见图2。
二、图2:编辑效果
说明:
3)保存:触发函数saveRow
保存当前行数据。
4)取消:触发函数cancelRow
还原当前行数据。
三、表格配置
// 表格配置
export const colConfig = [
{
type:'seq', // 列的类型:seq、checkbox、radio、expand
title:'序号',
align:'center'
},
{
title:'姓名', // 列标题(支持开启国际化)
field:'name', // 列字段名(注:属性层级越深,渲染性能就越差,例如:aa.bb.cc.dd.ee)
align:'center', // 对齐方式
editRender:{
// 可编辑渲染器配置项
name:'input' // 渲染器名称:input, textarea, select, $input, $select, $switch
}
},
{
title:'年龄',
field:'age',
align:'center',
editRender:{
name:'input'
}
},
{
title:'性别',
field:'sex',
align:'center',
editRender:{
name:'input'
}
}
]
// 表格数据
export const tableData = [
{
name:'小红',
age:15,
sex:'女',
id:1
},
{
name:'小白',
age:25,
sex:'男',
id:2
},
{
name:'小蓝',
age:21,
sex:'女',
id:3
}
]
四、代码实现
<template>
<div style="padding:100px">
<vxe-grid
ref="xTable"
:max-height="450"
v-bind="gridOptions"
show-overflow
keep-source
highlight-hover-row
highlight-current-row
resizable
auto-resize
:row-config="{ isCurrent: true, isHover: true,keyField:'id' }"
:edit-config="{trigger: 'manual', mode: 'row'}"
>
>
<template #operation="{ row }">
<vxe-button type="text" status="primary" @click="deleteRow(row)">删除</vxe-button>
<span v-if="$refs.xTable.isActiveByRow(row)">
<vxe-button type="text" status="primary" @click="saveRow()">保存</vxe-button>
<vxe-button type="text" status="primary" @click="cancelRow(row)">取消</vxe-button>
</span>
<span v-else>
<vxe-button type="text" status="primary" @click="editRow(row)">编辑</vxe-button>
</span>
</template>
</vxe-grid>
</div>
</template>
<script>
import {
colConfig, tableData } from './colConfig'
export default {
data() {
return {
gridOptions: {
columns: [],
data: [],
},
}
},
created() {
this.getTableData()
},
methods: {
getTableData() {
// 1.设置表格列
this.gridOptions.columns = colConfig
// 2.设置表格数据
this.gridOptions.data = tableData
// 3.添加操作列
let operationCol = {
title: '操作',
slots: {
default: 'operation' },
align: 'center'
}
this.gridOptions.columns.push(operationCol)
},
deleteRow(row) {
let index = this.gridOptions.data.findIndex(item => item.id === row.id)
this.gridOptions.data.splice(index, 1)
},
editRow(row) {
const $table = this.$refs.xTable
$table.setActiveRow(row)
},
saveRow() {
const $table = this.$refs.xTable
$table.clearActived().then(() => {
this.loading = true
setTimeout(() => {
this.loading = false
}, 300)
})
},
cancelRow(row) {
const $table = this.$refs.xTable
$table.clearActived().then(() => {
// 还原行数据
$table.revertData(row)
})
}
}
}
</script>