element中Table表格控件单选、多选功能进一步优化

一、代码实现

1、 父组件

<template>
   <div>
       <!-- 用户选择嵌套弹框 -->
		<el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="选择人员" :visible.sync="open"
			width="80%" append-to-body :show-close="false">
			<TableList :open="open" :dataList="dataList" @submitForm="submitForm" @cancel="cancel"></TableList>
		</el-dialog>
   </div>
</template>

<script>
import TableList from '@/components/table-list'
export default {
    name: 'TablePage5',
    components:{
        TableList,
    },
    props: {
      
    },
    data() {
        return {
            open:true,
            dataList:[ {
                        userId: 3,
                        userName: '王五'
                    },],
        }
    },
    watch: {
       
    },
    methods: {
        // 取消
		cancel() {
			// this.open = false
            // .............
		},
		// 确认
		submitForm(checkIds) {
			console.log(checkIds, 'checkId获取到')
            // .........
		},

    }
}
</script>

<style>

</style>

2、子组件(弹框)

<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
            <el-form-item label="搜索" prop="search">
                <el-input v-model="queryParams.search" placeholder="请输入" clearable size="small" style="width: 200px"
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery('queryForm')">搜索
                </el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
            </el-form-item>

        </el-form>
        <el-table v-loading="loading" :data="userList" max-height="400" ref="multipleTable" @select="selectRow"
            @select-all="selectAll" :header-cell-class-name="cellClass" :row-key="row => {
                return row.userId
            }
                ">
            <!-- reserve-selection="true" 仅对 type=selection 的列有效,类型为 Boolean,为 true 则会在数据更新之后保留之前选中的数据(需指定 row-key) -->
            <el-table-column type="selection" width="50" align="center" :reserve-selection="true" :selectable="selected" />
            <el-table-column type="index" width="100" :index="indexMethod" label="序号">
            </el-table-column>
            <el-table-column label="姓名" align="center" prop="userName" :show-overflow-tooltip="true" />
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum" :page-sizes="[2, 5, 10, 15]" :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
        <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" :autoScroll="false" /> -->
        <div class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
    </div>
</template>

<script>
// import { listPeople } from '@/api/manager/peopleList'
export default {
    name: 'TablePage5',
    props: {
        open: {
            type: Boolean,
            default: true
        },
        // 默认选中的数据
        dataList: {
            type: Array,
            default: () => {
                return []
            }
        },
        // 默认为0多选, 传递1单选
        type: {
            type: Number,
            default: 0
        }
    },
    data() {
        return {
            // 用户查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                search: ''
            },
            loading: false,
            // 用户列表(所有的用户数据)
            userList: [
                {
                    userId: 1,
                    userName: '张三'
                },
                {
                    userId: 2,
                    userName: '李四'
                },
                {
                    userId: 3,
                    userName: '王五'
                },
                {
                    userId: 4,
                    userName: '测试1'
                },
                {
                    userId: 5,
                    userName: '测试2'
                },
                {
                    userId: 6,
                    userName: '测试3'
                },
            ],
            // 用户总数
            total: 0,
            // 全选按钮隐藏
            DisableSelection: false,
            // 选中的人员列表
            checkList: [],
            // 选中的人员Id列表
            checkIds: []
        }
    },
    watch: {
        // 判断弹框是否显示
        open: {
            handler(val) {
                if (val) {
                    this.getList()
                }
            },
            immediate: true
        },
        // 父组件传递过来的之前已经选中的数据
        dataList: {
            handler(list) {
                this.checkList = list
                if(list){
                    this.checkIds = list.map(item=>item.userId)
                }
            },
            immediate: true,
            deep: true
        }
    },
    methods: {
        // 分页相关
        indexMethod(index) {
            // this.pageNum当前页码 // this.pageSize 每页条数
            return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
        },
        // 人员列表
        getList() {
            // 根据实际需求,调用对应接口...........
            // this.loading = true
            // listPeople(this.queryParams)
            //     .then(res => {
            //         console.log(res, '人员列表')
            //         this.userList = res.rows
            //         this.total = res.total
            //         this.loading = false
            //         数据回显
            //         this.selectedRecords()
            //     }).catch(err => {
            //         console.log(err)
            //         this.loading = false
            //     })

            // 数据回显
            this.selectedRecords()
        },
        // 数据回显 (之前选中的数据,和全部人员数据之间判断,如果userId相同,就表示选中,默认复选框选中)
        // toggleRowSelection 用于多选表格,切换某一行的选中状态,如果使用了第二个参数,则是设置这一行选中与否(selected 为 true 则选中)
        selectedRecords() {
            console.log(this.checkList, '数据回显')
            let that = this
            this.$nextTick(() => {
                this.userList.forEach((row) => {
                    this.checkList.forEach((child) => {
                        if (row.userId == child.userId) {
                            that.$refs.multipleTable.toggleRowSelection(row)
                        }
                    })
                })
            })
        },
        // 分页相关
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.queryParams.pageSize = val;
            this.getList()
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.queryParams.pageNum = val;
            this.getList()
        },
        // 选择人员弹框
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        // 选择人员重置
        resetQuery(queryForm) {
            this.$refs[queryForm].resetFields()
            this.queryParams.pageNum = 1
            this.getList()
        },

        // 全选:list所有选中的数据组成的列表
        selectAll(list) {
            console.log('全选', list)
            // list为空,表示全不选
            if (!list.length) { // 全不选
                // 将当前页表格的数据循环判断是否存在在checkList中,存在就删除
                this.userList.forEach((item) => {
                    this.checkList.forEach((child, key) => {
                        if (item.userId == child.userId) {
                            this.checkList.splice(key, 1)
                            this.checkIds.splice(key, 1)
                        }
                    })
                })
            } else { // 全选
                // 循环list,将不存在的值加上,已经存在的就不加了
                list.map((item) => {
                    if (this.checkIds.indexOf(item.userId) == -1) {
                        this.checkList.push(item)
                        this.checkIds.push(item.userId)
                    }
                })
            }
        },
        // 单选 list所有选中的数据组成的列表,  row当前选中或者取消选中的数据对象
        selectRow(list, row) {
            console.log('表格单选', list, row)
            let rowId = row.userId
            // 判断当前选项是否已经选择过了, -1表示不存在,没有选择过,  其余则是选择过了
            let isExist = -1
            this.checkList.forEach((item, index) => {
                if (row.userId == item.userId) {
                    isExist = index
                }
            })
            // row.id不存在在list中的时候,说明是取消勾选,undefined表示去除勾选
            let isDel = list.find(item => {
                return item.userId == rowId
            }) == undefined
            if (isDel) { //取消勾选
                // 去除,存在就删除
                if (isExist != -1) {
                    this.checkList.splice(isExist, 1)
                    this.checkIds.splice(isExist, 1)
                }
            } else { // 勾选
                // 添加
                if (isExist == -1) {
                    this.checkList.push(row)
                    this.checkIds.push(row.userId)
                }
            }
        },
        // 选择人员确认
        // clearSelection 用于多选表格,清空用户的选择
        submitForm() {
            let list = []
            this.checkList.map(item => {
                list.push(item.userId)
            })
            this.checkIds = list
            // 去重
            this.checkIds = [... new Set(this.checkIds)]
            // console.log(this.checkList,'this.checkList')
            // console.log(this.checkIds,'this.checkIds')
            this.$emit('submitForm', this.checkIds)
            // 清除复选框
            this.$refs.multipleTable.clearSelection()
           
        },
        // 取消按钮
        cancel() {
            this.$emit('cancel')
            // 清除复选框
            this.$refs.multipleTable.clearSelection()
        },
        // 超过1个人禁止选择 (当type为1时候,也就是单选时候)
        selected(row) {
            // 限制逻辑,返回 true 则为可勾选,反之则禁止勾选
            let judge = true
            if (this.checkList.length == 1 && this.type == 1) { // 单选
                judge = this.checkList.some(item => {
                    return item.userId == row.userId
                })
            }
            return judge
        },
        // 全选禁用 (当type为1时候,是单选,故全选按钮禁用)
        // 配合样式使用
        cellClass() {
            if (this.type == 1) {
                return 'DisableSelection'
            }
        }

    }
}
</script>

<style>
.dialog-footer {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 50px;
}

.el-table .DisableSelection .cell .el-checkbox__inner {
    display: none;
    position: relative;
}

.el-table .DisableSelection .cell:before {
    content: '';
    position: absolute;
}
</style>

二、效果图

在这里插入图片描述
在这里插入图片描述

  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值