以下是使用uni-ui组件库实现的可编辑表格代码示例:
- 定义表格数据结构:
data: {
columns: [
{
title: "姓名",
dataIndex: "name",
editable: true,
},
{
title: "年龄",
dataIndex: "age",
editable: true,
},
{
title: "性别",
dataIndex: "gender",
editable: true,
},
{
title: "操作",
dataIndex: "operation",
width: "100",
},
],
data: [
{
id: 1,
name: "张三",
age: 20,
gender: "男",
},
{
id: 2,
name: "李四",
age: 22,
gender: "女",
},
{
id: 3,
name: "王五",
age: 19,
gender: "男",
},
],
},
- 编写表格组件:
<template>
<view>
<uni-table-view :columns="columns" @click="handleClick">
<template slot="operation" slot-scope="{row}">
<uni-icon type="edit" @click="edit(row.id)" />
<uni-icon type="trash" @click="deleteItem(row.id)" />
</template>
</uni-table-view>
<uni-modal :visible="visible" title="编辑信息">
<view class="uni-form-item">
<view class="uni-form-item__label">姓名</view>
<uni-input v-model="currentItem.name" />
</view>
<view class="uni-form-item">
<view class="uni-form-item__label">年龄</view>
<uni-input v-model="currentItem.age" />
</view>
<view class="uni-form-item">
<view class="uni-form-item__label">性别</view>
<uni-radio-group v-model="currentItem.gender">
<uni-radio value="男">男</uni-radio>
<uni-radio value="女">女</uni-radio>
</uni-radio-group>
</view>
<view slot="footer">
<uni-button type="primary" @click="handleOk">确认</uni-button>
<uni-button @click="handleCancel">取消</uni-button>
</view>
</uni-modal>
</view>
</template>
- 实现数据渲染:
<uni-table-view :columns="columns" :data="data" @click="handleClick">
<template slot="operation" slot-scope="{row}">
<uni-icon type="edit" @click="edit(row.id)" />
<uni-icon type="trash" @click="deleteItem(row.id)" />
</template>
</uni-table-view>
- 添加编辑功能:
data() {
return {
// ...
visible: false,
currentItem: {},
};
},
methods: {
handleClick() {
this.visible = false;
},
edit(id) {
const item = this.data.find((item) => item.id === id);
this.currentItem = Object.assign({}, item);
this.visible = true;
},
handleOk() {
const index = this.data.findIndex(
(item) => item.id === this.currentItem.id
);
this.data[index] = Object.assign({}, this.currentItem);
this.visible = false;
},
handleCancel() {
this.visible = false;
},
},
- 添加删除功能:
deleteItem(id) {
const index = this.data.findIndex((item) => item.id === id);
this.data.splice(index, 1);
},
- 添加新增功能:
add() {
const id = this.data.length + 1;
const item = {
id,
name: "",
age: "",
gender: "男",
};
this.data.push(item);
this.edit(id);
},
- 数据提交功能:
handleSubmit() {
const formData = Object.assign({}, this.form);
this.data.push(formData);
this.form = {
name: "",
age: "",
gender: "男",
};
},
- 样式美化:
可以通过在style标签内添加CSS来美化表格。
以上是可编辑表格代码的基本实现,当然仍需通过修改适应自己的项目需求。