基于Vue3 + Element plus创建的表格
实现效果如下
<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>