前言
有时需要一些前端需求就是支持表格编辑,点击新增一行或者移除一行。这不马上搞一个示例代码出来了吗?方便以后复制粘贴,提升工作效率~
一、示例代码
(1)/src/views/Example/ElEditableTable/index.vue
<template>
<div class="table-container" style="padding: 100px;">
<el-table
border
size="small"
row-key="id"
height="300"
:data="tableList"
highlight-current-row
>
<el-table-column label="序号" width="100" align="center">
<template #default="scope">
<span>{
{ scope.$index + 1 }}</span>
</template>
</el-table-column>
<el-table-column prop="id" label="ID" width="180" align="center" />
<el-table-column prop="rpmName" label="名称" width="auto" align="center" show-overflow-tooltip>
<template #default="scope">
<div class="table-container-td__name">
<el-input size="small" v-model="scope.row.name" placeholder="请输入名称..." clearable></el-input>
</div>
</template>
</el-table-column>
<el-table-column label="操作" align="center" width="150">
<template #default="scope">
<div>
<el-button size="small" type="primary" plain @click="handleAddRow(scope.$index, scope.row, $event)" circle>
<el-icon :size="15"><Plus /></el-icon>
</el-button>
<el-button size="small" type="danger" plain @click="handleRemoveRow(scope.$index, scope.row, $event)" circle>
<el-icon :size="15"><Minus /></el-icon>
</el-button>
</div>
</template>
</el-table-column>
<template #empty>
<el-empty description="暂无数据"></el-empty>
</template>
</el-table>
</div>
</template>
<script setup>
import {
h, onMounted, onUnmounted, ref, getCurrentInstance, reactive, watch, nextTick } from 'vue'
// 代理对象
const {
proxy } = getCurrentInstance()
// 表格数据
const tableList = ref([
{
'id': parseInt(Math.random() * 10000) + '-' + new Date().getTime(), // 1234-1701741061535
'name': ''
}
])
/**
* 新增一行记录
*/
const handleAddRow = (index, row, event) => {
tableList.value.splice(index + 1, 0, {
'id': parseInt(Math.random() * 10000) + '-' + new Date().getTime(), // 1234-1701741061535
'name': '',
})
}
/**
* 新增一行记录
*/
const handleRemoveRow = (index, row, event) => {
if (tableList.value.length > 1) {
tableList.value.splice(index, 1)
} else {
proxy.$message({
type: 'warning', message: '必须保留一行哦!', duration: 2000 })
}
}
</script>