[vue] el-table implements dynamic addition of rows and columns

Implementation idea:
I recently encountered a requirement to dynamically increase rows and columns. When I got the requirement, I wanted to use the method that comes with el-table to achieve it, but after trying it, I found that it could not meet the desired requirement. There is no way but to write natively on the basis of el-table.
The general idea is as follows:
1. First, separate the rows and columns that need to be added dynamically in the table, define an array dataList to store the new row data, and define an array columnList to store the new column data.
2. Next, add a new button in front of the data in the specified column, and when you click the new button, request the interface to get the data.
3. Then process the obtained data, push the data of the table content to the dataList, and push the data of the header content to the columnList. Note that if the interface does not return the header data, you need to create the key-value of the corresponding column and store it in the columnList according to your specific needs.
(1) Rows can be added directly after the existing row, or a new row can be added after the specified row. For example: add a new line after the first line, use splice to add. splice (specified line, 0, added new line data)
(2) Click which line to add a new line after that line. Idea: Get the index of the currently clicked row and add it using splice. splice (specified row, 0, added new row data)
4. Finally, use dataList for el-table: data="dataList" and columnList for use
5. The above is the idea of ​​adding new rows and columns. If you want to delete rows and columns, you need to operate dataList and columnList through splice or slice. Delete the specified index position.
The general code is as follows:

<el-table :data="dataList">
	<el-table-column label="姓名" prop="name"></el-table-column>
	<!--动态列-->
	<el-table-column v-for="(it, index) in columnList" :key="index" :label="it.label">
		<!--动态行-->
		<template slot-scope="scope">
			<i class="el-icon-circle-plus-outline" @click="handleAddRow(scope.row, scope.$index)" />
			<span>{
    
    {
    
    scope.row.value}}</span>
			// 根据项目需求进行其他逻辑处理
		</template>
	</el-table-column>
</el-table>
export default {
    
    
	data() {
    
    
		return {
    
    
			dataList: [], // 表格数据
			columnList: [], //表头数据
		}
	},
	methods: {
    
    
		// 动态增加行
		async handleAddRow(row, index) {
    
    
			const data = await this.接口()
			data.forEach(d => {
    
    
				// 列添加
				this.columnList.push({
    
     label: '年龄' })
				// 行添加
			    this.dataList.splice(index, 0, d)
			})
		}
	}
}

Conclusion: The above is the general idea of ​​dynamically adding rows and columns to el-table, you can use it as a reference, and then refine it according to specific needs! ! ! Please point out the shortcomings, thank you

Guess you like

Origin blog.csdn.net/weixin_42342065/article/details/129692489
Recommended