vue ele ui实现全选
Vue + Element UI 实现全选功能
在 Vue 项目中使用 Element UI 实现表格全选功能,可以通过以下步骤完成:
准备工作
确保项目中已安装 Element UI 并正确引入。如果尚未安装,可以通过以下命令安装:

npm install element-ui
基础实现
在 Vue 组件中引入 Element UI 的表格组件,并设置相关数据和方法:

<template>
<el-table
ref="multipleTable"
:data="tableData"
@selection-change="handleSelectionChange"
style="width: 100%">
<el-table-column
type="selection"
width="55">
</el-table-column>
<el-table-column
prop="name"
label="姓名"
width="120">
</el-table-column>
<el-table-column
prop="age"
label="年龄"
width="120">
</el-table-column>
</el-table>
<div style="margin-top: 20px">
<el-button @click="toggleSelection">全选/取消全选</el-button>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [
{ name: '张三', age: 20 },
{ name: '李四', age: 22 },
{ name: '王五', age: 25 }
],
selectedRows: []
}
},
methods: {
toggleSelection() {
if (this.selectedRows.length === this.tableData.length) {
this.$refs.multipleTable.clearSelection()
} else {
this.tableData.forEach(row => {
this.$refs.multipleTable.toggleRowSelection(row)
})
}
},
handleSelectionChange(val) {
this.selectedRows = val
}
}
}
</script>
进阶功能
如果需要实现分页全选,可以结合分页组件和存储所有选中项的功能:
<template>
<el-table
ref="multipleTable"
:data="currentPageData"
@selection-change="handleSelectionChange"
style="width: 100%">
<!-- 表格列定义 -->
</el-table>
<el-pagination
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-size="pageSize"
layout="prev, pager, next"
:total="total">
</el-pagination>
<div>
<el-button @click="selectAll">全选所有页</el-button>
</div>
</template>
<script>
export default {
data() {
return {
allData: [], // 所有数据
currentPageData: [], // 当前页数据
currentPage: 1,
pageSize: 10,
total: 0,
selectedAll: false,
allSelectedRows: new Set() // 存储所有选中项
}
},
methods: {
handleCurrentChange(page) {
this.currentPage = page
this.updateCurrentPageData()
},
updateCurrentPageData() {
const start = (this.currentPage - 1) * this.pageSize
const end = start + this.pageSize
this.currentPageData = this.allData.slice(start, end)
},
handleSelectionChange(val) {
// 处理当前页选中项变化
},
selectAll() {
if (this.selectedAll) {
this.allSelectedRows.clear()
this.$refs.multipleTable.clearSelection()
} else {
this.allData.forEach(item => {
this.allSelectedRows.add(item)
})
this.updateCurrentPageSelection()
}
this.selectedAll = !this.selectedAll
},
updateCurrentPageSelection() {
this.$nextTick(() => {
this.currentPageData.forEach(row => {
if (this.allSelectedRows.has(row)) {
this.$refs.multipleTable.toggleRowSelection(row, true)
}
})
})
}
}
}
</script>
注意事项
- 使用
ref获取表格实例,通过toggleRowSelection方法控制行选中状态 - 分页全选时需要考虑数据量大时的性能问题
- 跨页选中时需要使用合适的数据结构(如 Set)存储所有选中项
- 注意在分页切换时更新当前页的选中状态
通过以上方法可以灵活实现 Element UI 表格的全选功能,根据实际需求选择基础实现或进阶功能。






