elementUI的table组件实现动态增删数据联动的可输入的表格
在使用Element UI的Table组件时,可以通过Vue的响应式数据特性来实现动态增删数据的功能,并确保数据的变化能够实时地在表格中体现出来。以下是一个简单的例子,展示了如何实现这个功能:
<template>
<div>
<el-button @click="addRow">添加行</el-button>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="date" label="日期" width="180">
</el-table-column>
<el-table-column prop="name" label="姓名" width="180">
<template slot-scope="scope">
<el-input v-model="scope.row.name"></el-input>
</template>
</el-table-column>
<el-table-column prop="address" label="地址">
<template slot-scope="scope">
<el-input v-model="scope.row.address"></el-input>
</template>
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button @click="deleteRow(scope.$index)">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
},
// ...可以添加更多行数据
]
}
},
methods: {
addRow() {
const newRow = { date: '新日期', name: '新姓名', address: '新地址' };
this.tableData.push(newRow);
},
deleteRow(index) {
this.tableData.splice(index, 1);
}
}
}
</script>
在这个例子中,tableData
是一个响应式数组,它存储了表格中所有的数据。通过点击“添加行”按钮来调用addRow
方法,在数组中添加一个新的空对象作为新行。在el-table-column
的template
插槽中,使用el-input
组件来实现可输入的单元格。点击“删除”按钮会调用deleteRow
方法,从数组中删除指定索引的行,实现表格数据的动态删除。
评论已关闭