需求场景:table表格,第一列为选择框,默认某几行数据为选中状态。
原文链接
template
<el-table
:data="roleData"
border
stripe
height="260"
style="margin:20px 0"
ref="docTable"
@select="(selection,row)=>{selectHandle(selection,row)}"
@select-all="(selection)=>{selectAllHandle(selection)}"
>
<el-table-column type="selection"></el-table-column>
<el-table-column label="角色名称" width="180" prop="name"></el-table-column>
<el-table-column label="角色权限" prop="role"></el-table-column>
</el-table>
data中定义存储数组
radios: []
mounted里面调用方法,获取后台数据
mounted() {
this.editForm = this.$parent.$parent.editForm
this.roleData = this.$parent.$parent.roleData
this.tableSelect = this.editForm.roleList
setTimeout(() => {
this.pickUp() //需要默认勾选的数据
}, 50)
},
methods方法
methods{
// 勾选全部表格数据
selectAllHandle(selection) {
// console.log(selection.length)
if (selection.length !== 0) {
selection.forEach((item) => {
if (!this.radios.includes(item.roleID)) {
this.radios.push(item.roleID)
}
})
} else {
this.radios = []
}
},
// 勾选表格某一行数据
selectHandle(selection, row) {
if (this.radios.includes(row.roleID)) {
this.radios.splice(this.radios.indexOf(row.roleID), 1)
} else {
this.radios.push(row.roleID)
}
// console.log(this.radios)
},
// 需要默认勾选的数据
pickUp() {
let arr = []
this.roleData.forEach((item) => {
this.tableSelect.forEach((val) => {
if (val.roleID === item.roleID) {
arr.push(item)
this.radios.push(item.roleID)
}
})
})
this.toggleSelection(arr)
},
// 默认选择中的行
toggleSelection(rows) {
// console.log(rows)
if (rows) {
rows.forEach((row) => {
this.$refs.docTable.toggleRowSelection(row)
})
} else {
this.$refs.docTable.clearSelection()
}
}
}