ElementUI中的el-table表格实现动态添加一行、删除一行、清空所有行
- 1、需求分析
- 2、代码实现
- HTML
- data
- methods
1、需求分析
ElementUI中的el-table中实现动态添加一行、删除一行、清空所有行
2、代码实现
HTML
<div class="middle-wrapper">
<el-button
type="primary"
icon="el-icon-plus"
size="mini"
@click="handleAddDetails"
>
添加
</el-button>
<el-button
type="success"
icon="el-icon-delete"
size="mini"
@click="handleDeleteDetails"
>
删除
</el-button>
<el-button
type="danger"
icon="el-icon-delete"
size="mini"
@click="handleDeleteAllDetails"
>
清空
</el-button>
</div>
<div class="bottom-wrapper">
<el-table
:data="outData2"
ref="timePeriodRef"
:row-class-name="rowClassName"
@selection-change="handleDetailSelectionChange"
:header-cell-style="{ 'text-align': 'center' }"
:cell-style="{ 'text-align': 'center' }"
border
@close="handleClose"
>
<el-table-column type="selection"></el-table-column>
<el-table-column
label="序号"
prop="idx"
width="50"
></el-table-column>
<el-table-column prop="beginTime" label="起始时间">
<template slot-scope="scope">
<el-time-select
v-model="scope.row.beginTime"
:picker-options="{
start: '00:00',
step: '00:15',
end: '24:00',
}"
placeholder="选择时间"
></el-time-select>
</template>
</el-table-column>
<el-table-column prop="endTime" label="结束时间">
<template slot-scope="scope">
<el-time-select
v-model="scope.row.endTime"
:picker-options="{
start: '00:00',
step: '00:15',
end: '24:00',
}"
placeholder="选择时间"
></el-time-select>
</template>
</el-table-column>
<el-table-column prop="status" label="充放电类型">
<template slot-scope="scope">
<el-select v-model="scope.row.status" placeholder="请选择">
<el-option
v-for="item in statusOptions"
:key="item.value"
:label="item.label"
:value="item.value"
></el-option>
</el-select>
</template>
</el-table-column>
<el-table-column prop="power" label="功率(KW)">
<template slot-scope="scope">
<el-input v-model="scope.row.power"></el-input>
</template>
</el-table-column>
</el-table>
</div>
data
data(){
return {
outData2: [],
//选中的从表数据
checkedDetail: [],
}
}
methods
methods:{
rowClassName({ row, rowIndex }) {
row.idx = rowIndex + 1
},
handleDetailSelectionChange(selection) {
if (selection.length > 1) {
this.$refs.timePeriodRef.clearSelection()
this.$refs.timePeriodRef.toggleRowSelection(selection.pop())
} else {
this.checkedDetail = selection
}
},
handleAddDetails() {
if (this.outData2 == undefined) {
this.outData2 = new Array()
}
let obj = {}
obj.beginTime = ''
obj.endTime = ''
obj.status = null
obj.power = ''
this.outData2.push(obj)
},
handleDeleteDetails() {
if (this.checkedDetail.length == 0) {
this.$alert('请先选择要删除的数据', '提示', {
confirmButtonText: '确定',
})
} else {
this.outData2.splice(this.checkedDetail[0].idx - 1, 1)
}
},
handleDeleteAllDetails() {
this.outData2 = []
},
}