vue3+ts利用el-table实现可编辑的表格
说明
在对表格数据进行操作时,如果数据项比较少,可通过自定义实现直接在表格中编辑。
界面展示
实现要点
- 使用slot来自定义单元格,实现输入、选择等操作
- 使用slot来自定义表头实现Add操作按钮在表头
- 使用v-if与v-else实现编辑状态与查看状态按钮的切换
代码
<template> <div> <el-table :data="userData"> <el-table-column label="Name" prop="name"> <template #default="scope"> <el-input v-if="activeIndex == scope.$index" v-model="scope.row.name"></el-input> <span v-else>{{ scope.row.name }}</span> </template> </el-table-column> <el-table-column label="Age" prop="age"> <template #default="scope"> <el-input type="number" v-if="activeIndex == scope.$index" v-model="scope.row.age"></el-input> <span v-else>{{ scope.row.age }}</span> </template> </el-table-column> <el-table-column label="Sex" prop="sex"> <template #default="scope"> <el-select v-if="activeIndex == scope.$index" v-model="scope.row.sex"> <el-option label="female" value="female"></el-option> <el-option label="male" value="male"></el-option> </el-select> <span v-else>{{ scope.row.sex }}</span> </template> </el-table-column> <el-table-column align="right" width="150"> <template #header> <el-button type="primary" @click="handleAdd">Add</el-button> </template> <template #default="scope"> <div v-if="activeIndex == scope.$index"> <el-button type="info" @click="handleSave">Save</el-button> </div> <div v-else> <el-button type="success" @click="handleEdit(scope.$index)">Edit</el-button> <el-popconfirm @confirm="handleDelete(scope.$index)" width="220" confirm-button-text="OK" cancel-button-text="No, Thanks" :icon="InfoFilled" icon-color="#626AEF" title="Are you sure to delete this?"> <template #reference> <el-button type="danger">Delete</el-button> </template> </el-popconfirm> </div> </template> </el-table-column> </el-table> </div> </template> <script setup lang="ts"> import { InfoFilled } from '@element-plus/icons-vue' import { reactive, ref } from 'vue'; interface iUser { name: string; age: number; sex: string; } let userData: iUser[] = reactive([ { name: 'nico', age: 18, sex: 'female' } ]); let activeIndex = ref<number>(-1); // 新增行 const handleAdd = function () { let item = { name: '', age: 0, sex: '' }; userData.push(item); activeIndex.value = userData.length - 1; }; // 编辑行 const handleEdit = (index: number) => { activeIndex.value = index; }; // 保存行 const handleSave = () => { activeIndex.value = -1; }; // 删除行 const handleDelete = function (index: number) { userData.splice(index, 1); }; </script>
分类:
项目开发
标签:
element-ui
, vue3
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了