vue3实现表格编辑和删除功能的示例代码
作者:huoyueyi
这篇文章主要为大家详细介绍了vue3实现表格编辑和删除功能的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
实现效果如下
实现代码
<template> <div class="table"> <div class="tableTop">现有数据集</div> <el-table :data="filterTableData" style="width: 100%" class-name="elTable" > <template #empty> <el-empty description="暂无数据" :image-size="200" /> </template> <el-table-column label="模型创建日期" prop="date" /> <el-table-column label="模型名称" prop="name" /> <el-table-column label="镜像地址" prop="address" /> <el-table-column align="right"> <template #header> <el-input v-model="search" size="small" placeholder="请输入您的模型名称" /> </template> <template #default="scope"> <el-button size="small" @click="handleEdit(scope.$index, scope.row)" >编辑</el-button > <el-button size="small" type="danger" @click="handleDelete(scope.$index)" >删除</el-button > </template> </el-table-column> </el-table> <el-dialog v-model="dialogVisible"> <el-form :model="editingRowData"> <el-form-item label="模型名称"> <el-input v-model="editingRowData.name" /> </el-form-item> </el-form> <div slot="footer"> <el-button @click="dialogVisible = false">取消</el-button> <el-button type="primary" @click="handleUpdate">保存</el-button> </div> </el-dialog> </div> </template> <script setup> import { ElInput, ElTable, ElTableColumn, ElIcon, ElButton, ElEmpty, ElMessageBox, ElMessage, ElDialog, ElForm, ElFormItem } from 'element-plus' import { computed, ref, reactive } from 'vue' const search = ref('') const editingRowData = ref({}) const dialogVisible = ref(false) // 编辑回显时的弹窗 let editIndex = -1 // 表示没有编辑的行 const tableData = reactive([ { date: '2023-05-03', name: 'Tom', address: 'https://mirrors.aliyun.com/' }, { date: '2023-05-02', name: 'John', address: 'http://mirrors.163.com/' }, { date: '2023-05-04', name: 'Morgan', address: 'https://mirrors.hust.edu.cn/' }, { date: '2023-05-01', name: 'Jessy', address: 'https://npm.taobao.org/' } ]) const handleEdit = (index, row) => { editIndex = index editingRowData.value = { ...row } dialogVisible.value = true } const handleUpdate = () => { if (editIndex !== -1) { tableData.splice(editIndex, 1, { ...editingRowData }) dialogVisible.value = false // tableData.value = editingRowData.value 直接赋值会失败,因为直接赋值只是赋值,而这里需要一个对象 tableData[editIndex] = Object.assign({}, editingRowData.value) ElMessage({ type: 'success', message: '修改成功' }) } else { ElMessage({ type: 'error', message: '修改失败!' }) } } const filterTableData = computed(function () { return tableData.filter(function (data) { return ( !search.value || data.name.toLowerCase().includes(search.value.toLowerCase()) ) }) }) // 删除数据集 const handleDelete = index => { ElMessageBox.confirm('您确定要删除该数据吗?', '警告', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { tableData.splice(index, 1) ElMessage({ type: 'success', message: '删除成功' }) }) } </script>
到此这篇关于vue3实现表格编辑和删除功能的示例代码的文章就介绍到这了,更多相关vue3表格编辑和删除内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!