To dynamically add and remove rows in an el-table
with input fields using element-plus
, you can use the following approach:
- Define a state variable in your component to store the table data:
Copy
data() {
return {
tableData: [
// initial data
]
}
}
- Render the
el-table
component with thetableData
as its data source:
xmlCopy
<el-table :data="tableData">
<!-- table columns -->
</el-table>
- To add a new row to the table, create a new object with the required properties and push it to the
tableData
array:
Copy
const newRow = { id: null, name: '', age: null }
this.tableData.push(newRow)
- To remove a row from the table, use the
splice
method to remove the row from thetableData
array:
basicCopy
this.tableData.splice(rowIndex, 1) // remove row at rowIndex
- To allow editing of the row data, you can use input fields within the
el-table-column
components:
pgsqlCopy
<el-table-column label="Name">
<template slot-scope="scope">
<el-input v-model="scope.row.name"></el-input>
</template>
</el-table-column>
Here, scope.row.name
is a two-way binding to the name
property of the current row in the el-table
.
Putting it all together, here’s an example component that demonstrates adding and removing rows with input fields in an el-table
:handlebarsCopy
<template>
<el-table :data="tableData">
<el-table-column label="ID">
<template slot-scope="scope">
<span>{{ scope.row.id }}</span>
</template>
</el-table-column>
<el-table-column label="Name">
<template slot-scope="scope">
<el-input v-model="scope.row.name"></el-input>
</template>
</el-table-column>
<el-table-column label="Age">
<template slot-scope="scope">
<el-input v-model="scope.row.age"></el-input>
</template>
</el-table-column>
<el-table-column>
<template slot-scope="scope">
<el-button @click="removeRow(scope.$index)">Remove</el-button>
</template>
</el-table-column>
</el-table>
<el-button @click="addRow">Add Row</el-button>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'John', age: 30 },
{ id: 2, name: 'Emily', age: 25 }
]
}
},
methods: {
addRow() {
const newRow = { id: null, name: '', age: null }
this.tableData.push(newRow)
},
removeRow(rowIndex) {
this.tableData.splice(rowIndex, 1)
}
}
}
</script>
Note that in this example, the Add Row
button calls the addRow
method, which adds a new row to the tableData
array. The Remove
button in each row calls the removeRow
method with the current row index, which removes the row from the tableData
array.