问题解释:
在使用Element 的Table组件时,如果发现自定义索引序号能够正常显示,但是在使用
selection-change
方法时无法检测到选中项,这可能是因为自定义索引序号与Table组件内部维护的选中状态不同步。
解决方法:
-
确保你在渲染表格行时使用正确的索引。
-
如果你使用了
v-for
来渲染表格行,确保你绑定的:key
是唯一的,并且不会导致不必要的渲染问题。 -
确保你的自定义索引序号与Table组件的选中状态同步。如果你使用了自定义索引,你可能需要在内部维护一个映射,将自定义索引映射到Table组件的实际数据数组的索引上。
附上代码:
<template>
<div>
<el-table
ref="multipleTable"
:data="tableData"
:fit="true"
empty-text="暂无数据"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection"></el-table-column>
<el-table-column label="序号" width="60">
<template slot-scope="scope">
{{ scope.$index + 1 }}
</template>
</el-table-column>
<el-table-column fixed="right" label="操作" width="240">
<template #default="scope">
<el-button type="danger" plain>
删除
</el-button>
<el-button type="primary" plain>
查看
</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
row-key:行数据的 Key,用来优化 Table 的渲染。
<template>
<div>
<!--
:row-key属性确保了每行数据的唯一性,使Table组件能够正确识别每一行数据
:row-key属性对于Table组件内部维护选中状态是必要的
handleSelectionChange方法用于响应选中项的变化
-->
<el-table
ref="multipleTable"
:data="tableData"
:fit="true"
row-key="id"
empty-text="暂无数据"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection"></el-table-column>
<el-table-column label="序号" width="60">
<template slot-scope="scope">
{{ scope.$index + 1 }}
</template>
</el-table-column>
<el-table-column fixed="right" label="操作" width="240">
<template #default="scope">
<el-button type="danger" plain>
删除
</el-button>
<el-button type="primary" plain>
查看
</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
name: "index",
data () {
return {
multipleSelection: [],
tableData: [
// 数据数组
]
}
},
methods: {
// 当选择项发生变化时会触发该事件
handleSelectionChange(val) {
this.multipleSelection = val
// console.log('查看选项变化', this.multipleSelection)
}
}
}
</script>
<style scoped lang="scss">
// 样式
</style>