亲宝软件园·资讯

展开

如何使用el-table+el-tree+el-select动态选择对应值

紫米粥 人气:0

使用el-table+el-select+el-tree来实现element中el-table表格动态选择对应值

背景描述:

项目组的老大让我们完成一个选择一个下拉框中的值,然后再动态选择该下拉框中树形结构的数值,说起来有点绕,给大家截个图,大家就一目了然了。

其实这个功能的实现主要借助与el-table、el-tree、el-select这三个组件就可以实现。

我碰到的问题:

(1)el-tree数据不显示。

(2)el-tree显示数据后无法绑定某一行。

(3)el-tree不能及时同步显示数据。

但是一开始做的时候一头雾水,因为我是做后端的,其实对前端的知识真的了解的不多,所以,在苦心钻研了一天终于参考了一篇大神的博客,成功解决的这个问题。

在这里附上原文地址:https:

解决问题:

根据大神的文章,我对其中的方法进行了主要的修改,然后按照大神的逻辑,重新修改了页面,发现就成功了,在这里具体什么原因其实我也不知道,但是在这里附上源码,方便大家进行参考。

其实核心主要是三大方面:

(1)第一步,选中下拉框,获取树形数据。

<el-form>
                <el-form-item label="用户地址" prop="aloWhTo">
                    <el-select v-model="form.aloWhTo" @change="testConsistent" placeholder="" readonly filterable style="width:95%" >
                        <el-option v-for="item in WarehouseOptions" :key="item.whId" :label="item.whName" :value="item.whId">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>

补充:大家在前端指导如何把数据转成树形结构吗?

其实很简单:只需要借助于handleTree()方法即可,但是在合理提前是你查询的数据是包含这种父子关系的字段的,比如我这里的wliFd这个字段就很关键。

listWarehouseLocationInfo(this.queryParamsByLocation).then(response => {
      this.WarehouseLocationInfoList = this.handleTree(response.data, 'wliId', 'wliFId')
      console.log("我是最终要返回的数据")
      console.log(this.WarehouseLocationInfoList)
      })

(2)通过@change="testConsistent"获取树形结构数据treeList,在这里我主要是模拟的树形数据。

 {
                            "searchValue": null,
                            "createBy": null,
                            "createTime": "2022-10-13 16:39:11",
                            "updateBy": null,
                            "updateTime": "2022-10-16 15:31:23",
                            "remark": null,
                            "params": {},
                            "parentName": null,
                            "parentId": null,
                            "orderNum": null,
                            "ancestors": null,
                            "children": [
                                {
                                    "searchValue": null,
                                    "createBy": null,
                                    "createTime": "2022-10-13 16:39:56",
                                    "updateBy": null,
                                    "updateTime": "2022-10-16 15:31:31",
                                    "remark": null,
                                    "params": {},
                                    "parentName": null,
                                    "parentId": null,
                                    "orderNum": null,
                                    "ancestors": null,
                                    "wliId": 5,
                                    "wliWhId": 28,
                                    "warehouseInformation": {
                                        "searchValue": null,
                                        "createBy": null,
                                        "createTime": null,
                                        "updateBy": null,
                                        "updateTime": null,
                                        "remark": null,
                                        "params": {},
                                        "whId": 28,
                                        "whCode": "2",
                                        "whName": "原材料1号仓",
                                        "whMnemonic": null,
                                        "whWcId": null,
                                        "category": null,
                                        "whProperty": null,
                                        "whPrincipalId": null,
                                        "salesUser": null,
                                        "whAddress": null,
                                        "whIsForever": null,
                                        "whIsVirtual": null,
                                        "whStatus": null,
                                        "delFlag": null,
                                        "remarks": null,
                                        "backup1": null,
                                        "backup2": null,
                                        "backup3": null
                                    },
                                    "wliFId": 4,
                                    "wliCode": "cz",
                                    "wliName": "长治",
                                    "wliMnemonic": "ZZ",
                                    "remarks": null
                                },
                                {
                                    "searchValue": null,
                                    "createBy": null,
                                    "createTime": "2022-10-13 16:40:19",
                                    "updateBy": null,
                                    "updateTime": null,
                                    "remark": null,
                                    "params": {},
                                    "parentName": null,
                                    "parentId": null,
                                    "orderNum": null,
                                    "ancestors": null,
                                    "wliId": 6,
                                    "wliWhId": 28,
                                    "warehouseInformation": {
                                        "searchValue": null,
                                        "createBy": null,
                                        "createTime": null,
                                        "updateBy": null,
                                        "updateTime": null,
                                        "remark": null,
                                        "params": {},
                                        "whId": 28,
                                        "whCode": "2",
                                        "whName": "原材料1号仓",
                                        "whMnemonic": null,
                                        "whWcId": null,
                                        "category": null,
                                        "whProperty": null,
                                        "whPrincipalId": null,
                                        "salesUser": null,
                                        "whAddress": null,
                                        "whIsForever": null,
                                        "whIsVirtual": null,
                                        "whStatus": null,
                                        "delFlag": null,
                                        "remarks": null,
                                        "backup1": null,
                                        "backup2": null,
                                        "backup3": null
                                    },
                                    "wliFId": 4,
                                    "wliCode": "ty",
                                    "wliName": "太原",
                                    "wliMnemonic": "TY",
                                    "remarks": null
                                }
                            ],
                            "wliId": 4,
                            "wliWhId": 28,
                            "warehouseInformation": {
                                "searchValue": null,
                                "createBy": null,
                                "createTime": null,
                                "updateBy": null,
                                "updateTime": null,
                                "remark": null,
                                "params": {},
                                "whId": 28,
                                "whCode": "2",
                                "whName": "原材料1号仓",
                                "whMnemonic": null,
                                "whWcId": null,
                                "category": null,
                                "whProperty": null,
                                "whPrincipalId": null,
                                "salesUser": null,
                                "whAddress": null,
                                "whIsForever": null,
                                "whIsVirtual": null,
                                "whStatus": null,
                                "delFlag": null,
                                "remarks": null,
                                "backup1": null,
                                "backup2": null,
                                "backup3": null
                            },
                            "wliFId": 0,
                            "wliCode": "sx",
                            "wliName": "山西",
                            "wliMnemonic": "SX",
                            "remarks": null
                        }
                    ];
                console.log(this.form.aloWhTo)
                if(this.form.aloWhTo === 2){
                    this.treeList = data;
                }else {
                    this.treeList = null;
                }
            },

(3)修改el-table中的el-table-column,并将el-select、el-tree进行数据绑定,这里具体的参数大家可以参照我推荐的大神的博客,在这里我就不一一介绍了。

 <el-table-column label="地址" prop="address">
                    <template slot-scope="scope">
                    <el-select
                            :ref="'address' + scope.$index"
                            v-model="userlist[scope.$index]['address']"
                            placeholder="请选择地址类别"
                            clearable
                    >
                        <el-option :value="userlist[scope.$index]['address']" style="height: auto">
                            <el-tree
                                    :ref="'addressTree' + scope.$index"
                                    :data="treeList"
                                    node-key="wliId"
                                    :props="defaultPropsList"
                                    @node-click="getTypeList(scope.$index)"
                            >
                                <span slot-scope="{ node }">{{ node.label }}</span>
                            </el-tree>
                        </el-option>

                    </el-select>
                </template>
                </el-table-column>

(4)编写getTypeList(scope.$index),这个方法才是核心,大家按照这个逻辑改一下ref的名字还有数据表的名字即可使用,方便快捷,并且能够实现相应的功能。

 getTypeList(index) {
                // .getCurrentKey()获取到当前要选择节点的key值
                // 使用此方法必须设置 node-key 属性,若没有节点被选中则返回 null
                const nodeId = this.$refs['addressTree' + index].getCurrentKey()
                // .getNode(nodeId) 根据 data 或者 key 拿到 Tree 组件中的 node
                const node = this.$refs['addressTree' + index].getNode(nodeId)
                // 根据index给当前元素的categoryName参数赋值
                this.$set(this.userlist[index], 'address', node.label)
                //this.$set(this.userlist[index], 'categoryNo', node.data.docTypeNo)
                // 此时页面上已经可以动态选择
                // 这一步是通过判断当前元素的v-model是否有值来控制el-option是否隐藏
                if (this.userlist[index].address) {
                    // .blur()用来隐藏当前展开的下拉选择框
                    this.$refs['address' + index].blur()
                }
            },

至此到这里就全部结束了。

(5)在这里附上整个页面的所有代码,方便大家可以再本地进行测试。

<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <!-- 搜索与添加区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>

            <el-form>
                <el-form-item label="用户地址" prop="aloWhTo">
                    <el-select v-model="form.aloWhTo" @change="testConsistent" placeholder="" readonly filterable style="width:95%" >
                        <el-option v-for="item in WarehouseOptions" :key="item.whId" :label="item.whName" :value="item.whId">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>

            <!-- 用户列表区域 -->
            <el-table :data="userlist" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>

                <el-table-column label="地址">
                    <template>
                        <el-select v-model="testValue" placeholder="请选择" style="width:140px">
                            <el-option :value="treeDataValue" style="height: auto">
                                <el-tree :data="treeList" :props="defaultPropsList" @node-click="handleNodeClick"></el-tree>
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column label="地址" prop="address">
                    <template slot-scope="scope">
                    <el-select
                            :ref="'address' + scope.$index"
                            v-model="userlist[scope.$index]['address']"
                            placeholder="请选择地址类别"
                            clearable
                    >
                        <el-option :value="userlist[scope.$index]['address']" style="height: auto">
                            <el-tree
                                    :ref="'addressTree' + scope.$index"
                                    :data="treeList"
                                    node-key="wliId"
                                    :props="defaultPropsList"
                                    @node-click="getTypeList(scope.$index)"
                            >
                                <span slot-scope="{ node }">{{ node.label }}</span>
                            </el-tree>
                        </el-option>

                    </el-select>
                </template>
                </el-table-column>


                <el-table-column label="操作" width="180px">
                    <template slot-scope="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
                        <!-- 分配角色按钮 -->
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </el-card>




















        <!-- 添加用户的对话框 -->
        <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
            <!-- 内容主体区域 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
        </el-dialog>

        <!-- 修改用户的对话框 -->
        <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
        </el-dialog>

        <!-- 分配角色的对话框 -->
        <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="setRoleDialogClosed">
            <div>
                <p>当前的用户:{{userInfo.username}}</p>
                <p>当前的角色:{{userInfo.role_name}}</p>
                <p>分配新角色:
                    <el-select v-model="selectedRoleId" placeholder="请选择">
                        <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "user",
        data() {
            // 验证邮箱的规则
            var checkEmail = (rule, value, cb) => {
                // 验证邮箱的正则表达式
                const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

                if (regEmail.test(value)) {
                    // 合法的邮箱
                    return cb()
                }

                cb(new Error('请输入合法的邮箱'))
            }

            // 验证手机号的规则
            var checkMobile = (rule, value, cb) => {
                // 验证手机号的正则表达式
                const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

                if (regMobile.test(value)) {
                    return cb()
                }

                cb(new Error('请输入合法的手机号'))
            }

            return {
                testValue:"",
                treeDataValue:"",
                treeList:undefined,

                defaultPropsList: {
                    children: 'children',
                    label: 'wliName'
                },

                data: [{
                    label: '一级 1',
                    children: [{
                        label: '二级 1-1',
                        children: [{
                            label: '三级 1-1-1'
                        }]
                    }]
                }, {
                    label: '一级 2',
                    children: [{
                        label: '二级 2-1',
                        children: [{
                            label: '三级 2-1-1'
                        }]
                    }, {
                        label: '二级 2-2',
                        children: [{
                            label: '三级 2-2-1'
                        }]
                    }]
                }, {
                    label: '一级 3',
                    children: [{
                        label: '二级 3-1',
                        children: [{
                            label: '三级 3-1-1'
                        }]
                    }, {
                        label: '二级 3-2',
                        children: [{
                            label: '三级 3-2-1'
                        }]
                    }]
                }],
                form:{},
                WarehouseOptions:[
                    {
                    whId:2,
                    whName:"有的"
                },
                    {
                        whId:3,
                        whName:"没有"
                    }
                ],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                // 获取用户列表的参数对象
                queryInfo: {
                    query: '',
                    // 当前的页数
                    pagenum: 1,
                    // 当前每页显示多少条数据
                    pagesize: 10
                },
                userlist: [],
                total: 0,
                // 控制添加用户对话框的显示与隐藏
                addDialogVisible: false,
                // 添加用户的表单数据
                addForm: {
                    username: '',
                    password: '',
                    email: '',
                    mobile: ''
                },
                // 添加表单的验证规则对象
                addFormRules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        {
                            min: 3,
                            max: 10,
                            message: '用户名的长度在3~10个字符之间',
                            trigger: 'blur'
                        }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        {
                            min: 6,
                            max: 15,
                            message: '用户名的长度在6~15个字符之间',
                            trigger: 'blur'
                        }
                    ],
                    email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur' },
                        { validator: checkEmail, trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, message: '请输入手机号', trigger: 'blur' },
                        { validator: checkMobile, trigger: 'blur' }
                    ]
                },
                // 控制修改用户对话框的显示与隐藏
                editDialogVisible: false,
                // 查询到的用户信息对象
                editForm: {},
                // 修改表单的验证规则对象
                editFormRules: {
                    email: [
                        { required: true, message: '请输入用户邮箱', trigger: 'blur' },
                        { validator: checkEmail, trigger: 'blur' }
                    ],
                    mobile: [
                        { required: true, message: '请输入用户手机', trigger: 'blur' },
                        { validator: checkMobile, trigger: 'blur' }
                    ]
                },
                // 控制分配角色对话框的显示与隐藏
                setRoleDialogVisible: false,
                // 需要被分配角色的用户信息
                userInfo: {},
                // 所有角色的数据列表
                rolesList: [],
                // 已选中的角色Id值
                selectedRoleId: ''
            }
        },
        created() {
            this.getUserList()
        },
        methods: {
            testConsistent(){
                const data = [
                        {
                            "searchValue": null,
                            "createBy": null,
                            "createTime": "2022-10-13 16:39:11",
                            "updateBy": null,
                            "updateTime": "2022-10-16 15:31:23",
                            "remark": null,
                            "params": {},
                            "parentName": null,
                            "parentId": null,
                            "orderNum": null,
                            "ancestors": null,
                            "children": [
                                {
                                    "searchValue": null,
                                    "createBy": null,
                                    "createTime": "2022-10-13 16:39:56",
                                    "updateBy": null,
                                    "updateTime": "2022-10-16 15:31:31",
                                    "remark": null,
                                    "params": {},
                                    "parentName": null,
                                    "parentId": null,
                                    "orderNum": null,
                                    "ancestors": null,
                                    "wliId": 5,
                                    "wliWhId": 28,
                                    "warehouseInformation": {
                                        "searchValue": null,
                                        "createBy": null,
                                        "createTime": null,
                                        "updateBy": null,
                                        "updateTime": null,
                                        "remark": null,
                                        "params": {},
                                        "whId": 28,
                                        "whCode": "2",
                                        "whName": "原材料1号仓",
                                        "whMnemonic": null,
                                        "whWcId": null,
                                        "category": null,
                                        "whProperty": null,
                                        "whPrincipalId": null,
                                        "salesUser": null,
                                        "whAddress": null,
                                        "whIsForever": null,
                                        "whIsVirtual": null,
                                        "whStatus": null,
                                        "delFlag": null,
                                        "remarks": null,
                                        "backup1": null,
                                        "backup2": null,
                                        "backup3": null
                                    },
                                    "wliFId": 4,
                                    "wliCode": "cz",
                                    "wliName": "长治",
                                    "wliMnemonic": "ZZ",
                                    "remarks": null
                                },
                                {
                                    "searchValue": null,
                                    "createBy": null,
                                    "createTime": "2022-10-13 16:40:19",
                                    "updateBy": null,
                                    "updateTime": null,
                                    "remark": null,
                                    "params": {},
                                    "parentName": null,
                                    "parentId": null,
                                    "orderNum": null,
                                    "ancestors": null,
                                    "wliId": 6,
                                    "wliWhId": 28,
                                    "warehouseInformation": {
                                        "searchValue": null,
                                        "createBy": null,
                                        "createTime": null,
                                        "updateBy": null,
                                        "updateTime": null,
                                        "remark": null,
                                        "params": {},
                                        "whId": 28,
                                        "whCode": "2",
                                        "whName": "原材料1号仓",
                                        "whMnemonic": null,
                                        "whWcId": null,
                                        "category": null,
                                        "whProperty": null,
                                        "whPrincipalId": null,
                                        "salesUser": null,
                                        "whAddress": null,
                                        "whIsForever": null,
                                        "whIsVirtual": null,
                                        "whStatus": null,
                                        "delFlag": null,
                                        "remarks": null,
                                        "backup1": null,
                                        "backup2": null,
                                        "backup3": null
                                    },
                                    "wliFId": 4,
                                    "wliCode": "ty",
                                    "wliName": "太原",
                                    "wliMnemonic": "TY",
                                    "remarks": null
                                }
                            ],
                            "wliId": 4,
                            "wliWhId": 28,
                            "warehouseInformation": {
                                "searchValue": null,
                                "createBy": null,
                                "createTime": null,
                                "updateBy": null,
                                "updateTime": null,
                                "remark": null,
                                "params": {},
                                "whId": 28,
                                "whCode": "2",
                                "whName": "原材料1号仓",
                                "whMnemonic": null,
                                "whWcId": null,
                                "category": null,
                                "whProperty": null,
                                "whPrincipalId": null,
                                "salesUser": null,
                                "whAddress": null,
                                "whIsForever": null,
                                "whIsVirtual": null,
                                "whStatus": null,
                                "delFlag": null,
                                "remarks": null,
                                "backup1": null,
                                "backup2": null,
                                "backup3": null
                            },
                            "wliFId": 0,
                            "wliCode": "sx",
                            "wliName": "山西",
                            "wliMnemonic": "SX",
                            "remarks": null
                        }
                    ];
                console.log(this.form.aloWhTo)
                if(this.form.aloWhTo === 2){
                    this.treeList = data;
                }else {
                    this.treeList = null;
                }
            },
            getTypeList(index) {
                // .getCurrentKey()获取到当前要选择节点的key值
                // 使用此方法必须设置 node-key 属性,若没有节点被选中则返回 null
                const nodeId = this.$refs['addressTree' + index].getCurrentKey()
                // .getNode(nodeId) 根据 data 或者 key 拿到 Tree 组件中的 node
                const node = this.$refs['addressTree' + index].getNode(nodeId)
                // 根据index给当前元素的categoryName参数赋值
                this.$set(this.userlist[index], 'address', node.label)
                //this.$set(this.userlist[index], 'categoryNo', node.data.docTypeNo)
                // 此时页面上已经可以动态选择
                // 这一步是通过判断当前元素的v-model是否有值来控制el-option是否隐藏
                if (this.userlist[index].address) {
                    // .blur()用来隐藏当前展开的下拉选择框
                    this.$refs['address' + index].blur()
                }
            },


            handleNodeClick(data) {
                console.log(data);
                this.testValue = data.wliName;
                console.log(this.testValue)
            },
            getUserList() {
                // const { data: res } = await this.$http.get('users', {
                //     params: this.queryInfo
                // })
                // if (res.meta.status !== 200) {
                //     return this.$message.error('获取用户列表失败!')
                // }
                // console.log("获取用户信息")
                // console.log(res)
                var res = {
                    "data": {
                        "total": 6,
                        "pagenum": 1,
                        "users": [
                            {
                                "id": 500,
                                "role_name": "超级管理员",
                                "username": "admin",
                                "create_time": 1486720211,
                                "mobile": "12345678",
                                "email": "adsfad@qq.com",
                                "mg_state": true
                            },
                            {
                                "id": 502,
                                "role_name": "测试角色2",
                                "username": "linken",
                                "create_time": 1486720211,
                                "mobile": "1213213123",
                                "email": "asdf@qq.com",
                                "mg_state": true
                            },
                            {
                                "id": 508,
                                "role_name": "主管",
                                "username": "asdf1",
                                "create_time": 1511853015,
                                "mobile": "123123",
                                "email": "adfsa@qq.com",
                                "mg_state": true
                            },
                            {
                                "id": 509,
                                "role_name": "test",
                                "username": "asdf123",
                                "create_time": 1511853353,
                                "mobile": "1111",
                                "email": "asdf@qq.com",
                                "mg_state": false
                            },
                            {
                                "id": 510,
                                "role_name": "超级管理员",
                                "username": "lingyi",
                                "create_time": 1664245645,
                                "mobile": "18998999999",
                                "email": "2311229622@qq.com",
                                "mg_state": true
                            },
                            {
                                "id": 511,
                                "role_name": "超级管理员",
                                "username": "123",
                                "create_time": 1664246336,
                                "mobile": "15166578443",
                                "email": "2499070273@qq.com",
                                "mg_state": false
                            }
                        ]
                    },
                    "meta": {
                        "msg": "获取管理员列表成功",
                        "status": 200
                    }
                };
                this.userlist = res.data.users
                this.total = res.data.total
                console.log(res)
            },
            // 监听 pagesize 改变的事件
            handleSizeChange(newSize) {
                // console.log(newSize)
                this.queryInfo.pagesize = newSize
                this.getUserList()
            },
            // 监听 页码值 改变的事件
            handleCurrentChange(newPage) {
                console.log(newPage)
                this.queryInfo.pagenum = newPage
                this.getUserList()
            },
            // 监听 switch 开关状态的改变
            async userStateChanged(userinfo) {
                console.log(userinfo)
                const { data: res } = await this.$http.put(
                    `users/${userinfo.id}/state/${userinfo.mg_state}`
                )
                if (res.meta.status !== 200) {
                    userinfo.mg_state = !userinfo.mg_state
                    return this.$message.error('更新用户状态失败!')
                }
                this.$message.success('更新用户状态成功!')
            },
            // 监听添加用户对话框的关闭事件
            addDialogClosed() {
                this.$refs.addFormRef.resetFields()
            },
            // 点击按钮,添加新用户
            addUser() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) return
                    // 可以发起添加用户的网络请求
                    const { data: res } = await this.$http.post('users', this.addForm)

                    if (res.meta.status !== 201) {
                        this.$message.error('添加用户失败!')
                    }

                    this.$message.success('添加用户成功!')
                    // 隐藏添加用户的对话框
                    this.addDialogVisible = false
                    // 重新获取用户列表数据
                    this.getUserList()
                })
            },
            // 展示编辑用户的对话框
            async showEditDialog(id) {
                // console.log(id)
                const { data: res } = await this.$http.get('users/' + id)

                if (res.meta.status !== 200) {
                    return this.$message.error('查询用户信息失败!')
                }

                this.editForm = res.data
                this.editDialogVisible = true
            },
            // 监听修改用户对话框的关闭事件
            editDialogClosed() {
                this.$refs.editFormRef.resetFields()
            },
            // 修改用户信息并提交
            editUserInfo() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) return
                    // 发起修改用户信息的数据请求
                    const { data: res } = await this.$http.put(
                        'users/' + this.editForm.id,
                        {
                            email: this.editForm.email,
                            mobile: this.editForm.mobile
                        }
                    )

                    if (res.meta.status !== 200) {
                        return this.$message.error('更新用户信息失败!')
                    }

                    // 关闭对话框
                    this.editDialogVisible = false
                    // 刷新数据列表
                    this.getUserList()
                    // 提示修改成功
                    this.$message.success('更新用户信息成功!')
                })
            },
            // 根据Id删除对应的用户信息
            async removeUserById(id) {
                // 弹框询问用户是否删除数据
                const confirmResult = await this.$confirm(
                    '此操作将永久删除该用户, 是否继续?',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).catch(err => err)

                // 如果用户确认删除,则返回值为字符串 confirm
                // 如果用户取消了删除,则返回值为字符串 cancel
                // console.log(confirmResult)
                if (confirmResult !== 'confirm') {
                    return this.$message.info('已取消删除')
                }

                const { data: res } = await this.$http.delete('users/' + id)

                if (res.meta.status !== 200) {
                    return this.$message.error('删除用户失败!')
                }

                this.$message.success('删除用户成功!')
                this.getUserList()
            },
            // 展示分配角色的对话框
            async setRole(userInfo) {
                this.userInfo = userInfo

                // 在展示对话框之前,获取所有角色的列表
                const { data: res } = await this.$http.get('roles')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取角色列表失败!')
                }

                this.rolesList = res.data

                this.setRoleDialogVisible = true
            },
            // 点击按钮,分配角色
            async saveRoleInfo() {
                if (!this.selectedRoleId) {
                    return this.$message.error('请选择要分配的角色!')
                }

                const { data: res } = await this.$http.put(
                    `users/${this.userInfo.id}/role`,
                    {
                        rid: this.selectedRoleId
                    }
                )

                if (res.meta.status !== 200) {
                    return this.$message.error('更新角色失败!')
                }

                this.$message.success('更新角色成功!')
                this.getUserList()
                this.setRoleDialogVisible = false
            },
            // 监听分配角色对话框的关闭事件
            setRoleDialogClosed() {
                this.selectedRoleId = ''
                this.userInfo = {}
            }
        }
    }
</script>

<style lang="less" scoped>
</style>

总结

加载全部内容

相关教程
猜你喜欢
用户评论