el-table-column循环出来的 怎么给每一列添加sort-method传参key呢
时间: 2023-11-08 20:09:19 浏览: 125
可以通过使用作用域插槽来实现这个功能。在 `el-table-column` 上定义一个 `scopedSlots` 属性,然后在模板里面使用作用域插槽来渲染每一列:
```html
<template>
<el-table :data="tableData" border>
<el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label" :sortable="true" :sort-method="column.sortMethod" :width="column.width">
<template v-if="column.scopedSlot" v-slot="scope">
<slot :name="column.scopedSlot" v-bind="scope"></slot>
</template>
</el-table-column>
</el-table>
</template>
```
可以看到,我们在 `el-table-column` 上添加了 `:sort-method="column.sortMethod"` 属性,其中 `column.sortMethod` 是一个函数,用于自定义排序方法。同时,我们还添加了一个作用域插槽,用于渲染自定义的内容。
在组件中,我们可以定义一个 `columns` 数组,用于存储表格的列信息:
```js
export default {
data() {
return {
tableData: [],
columns: [
{ label: '姓名', prop: 'name', width: '120px', sortMethod: this.sortByName },
{ label: '年龄', prop: 'age', width: '120px', sortMethod: this.sortByAge },
{ label: '性别', prop: 'gender', width: '120px' },
{ label: '地址', prop: 'address' },
{ label: '操作', width: '120px', scopedSlot: 'actions' }
]
};
},
methods: {
sortByName(a, b) {
return a.name.localeCompare(b.name);
},
sortByAge(a, b) {
return a.age - b.age;
}
}
};
```
可以看到,我们在 `columns` 数组中定义了每一列的 `label`、`prop`、`width` 和 `sortMethod` 属性。其中,`sortMethod` 是一个函数,用于自定义排序方法。我们还可以在 `columns` 数组中定义一个 `scopedSlot` 属性,用于渲染自定义的内容。
最后,在模板中使用作用域插槽来渲染自定义的内容:
```html
<template>
<el-table :data="tableData" border>
<el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label" :sortable="true" :sort-method="column.sortMethod" :width="column.width">
<template v-if="column.scopedSlot" v-slot="scope">
<slot :name="column.scopedSlot" v-bind="scope"></slot>
</template>
<template v-else-if="column.prop === 'gender'">
{{ scope.row.gender === 1 ? '男' : '女' }}
</template>
</el-table-column>
<el-table-column label="操作" width="120px">
<template v-slot:actions="{ row }">
<el-button type="text" @click="handleEdit(row)">编辑</el-button>
<el-button type="text" @click="handleDelete(row)">删除</el-button>
</template>
</el-table-column>
</el-table>
</template>
```
可以看到,我们在 `el-table-column` 中使用了 `v-if` 和 `v-else-if` 来渲染不同的内容。如果当前列有 `scopedSlot` 属性,则使用作用域插槽来渲染自定义的内容;否则,根据 `prop` 属性渲染不同的内容。在这个例子中,我们根据 `gender` 属性来渲染不同的性别文本,根据 `actions` 属性来渲染操作按钮。
阅读全文
相关推荐


















