需求前提:vue3 + element-plus,动态添加删除行,行内放input输入框 / select下拉框。
一、基本实现
1、html 代码:
<div class="box">
<el-table :data="tableData" border style="width: 88%;margin: 0 auto;">
<el-table-column label="序号" align="center" width="80">
<template #default="scope">
<span>{{ scope.$index + 1 }}</span>
</template>
</el-table-column>
<el-table-column prop="type" label="交易类型" align="center" width="120">
<template #default="scope">
<el-select v-model="scope.row.type" style="width:90px" size="small" clearable>
<el-option v-for="item in transType" :key="item.value" :label="item.label" :value="item.value"/>
</el-select>
</template>
</el-table-column>
<el-table-column prop="days" label="考核天数" align="center" width="114">
<template #default="scope">
<el-input v-model="scope.row.days" size="small"></el-input>
</template>
</el-table-column>
<el-table-column prop="amount" label="交易考核金额" align="center" width="120">
<template #default="scope">
<el-input v-model="scope.row.amount" size="small"></el-input>
</template>
</el-table-column>
<el-table-column label="备注" align="center" width="120">
<template #default="scope">
<span>第{{ scope.$index + 1 }}次提交</span>
</template>
</el-table-column>
<el-table-column label="操作" align="center" fixed="right" width="62">
<template #default="scope">
<el-button @click="deleteTableData(scope.row)" link icon="Delete" type="primary"></el-button>
</template>
</el-table-column>
</el-table>
<el-icon @click="addTableData" class="icon" size="24" color="#fb7a14"><CirclePlusFilled /></el-icon>
</div>
2、js 代码:
<script setup>
import { ref } from 'vue';
const tableData = ref([])
// 新增一行
const addTableData = ()=>{
const newRow = {
type: null,
days: null,
amount: null
}
tableData.value.push(newRow)
}
// 删除
const deleteTableData = (row) =>{
const index = tableData.value.indexOf(row);
if (index !== -1) {
tableData.value.splice(index, 1);
}
}
</script>
3、css 代码:
<style lang='scss' scoped>
.box{
position: relative;
.icon{
position: absolute;
bottom:10px;
right: 19px;
}
}
</style>
4、效果展示:
注:点击加号图标时,动态从尾部添加一行,点击某行的删除图标,则删除该行;
二、拓展
注:以上动态添加空行,如果需要添加后端返回的数据;则添加时,把后端返回的值拼到原数组后面即可。
如下,原始数据已有一条记录,点击加号,动态添加两条数据:
const tableData = ref([
{
type: 1,
days: '11',
amount: '111'
}
])
// 新增一行
const addTableData = ()=>{
const newRow = [
{
type: 3,
days: '22',
amount: '222'
},
{
type: 5,
days: '33',
amount: '333'
},
]
tableData.value = tableData.value.concat(newRow)
}
**tips:**交易类型是个下拉框,自己定义即可,参考如下:
const transType = [
{value: 1, label: '贷记卡'},
{value: 2, label: '借记卡'},
{value: 3, label: '支付宝'},
{value: 4, label: '微信'},
{value: 5, label: '云闪付'}
]
:希望对大家有所帮助,好运来~