Skip to content

部门管理

使用 layui treeTable 进行渲染

显示部门数据列表

1、部门表格占位

html
<div style="padding: 16px">
  <div class="layui-card">
    <div class="layui-card-body">
      <table
        class="layui-hide"
        id="department-table"
        lay-filter="department-table"
      ></table>
    </div>
  </div>
</div>

2、请求后端接口数据,渲染表格

请求接口 /api/v1/department/treetable 用来获取 treeTable 表格的数据。

javascript
layui.use(function () {
  var treeTable = layui.treeTable;
  var $ = layui.$;
  var form = layui.form;

  treeTable.render({
    elem: "#department-treeTable",
    id: "department-treeTable",
    url: "/api/v1/department/treetable",
    height: "full-35",
    toolbar: "#department-toolbar",
    page: true,
    cols: [
      [
        { field: "id", title: "ID", width: 80, sort: true },
        { field: "name", title: "部门名", width: 220 },
        { field: "leader", title: "负责人", width: 160 },
        { field: "enable", title: "状态", width: 80 },
        {
          fixed: "right",
          title: "操作",
          width: 120,
          align: "center",
          toolbar: "#department-tool",
        },
      ],
    ],
  });
});

3、后端接口返回数据

python
@department_api.get('/department/treetable')
def get_list_as_treetable():
    q = db.select(DepartmentORM)
    q = q.where(DepartmentORM.pid == 0)
    dept_orm_list = db.session.execute(q).scalars()
    ret = []
    for child in dept_orm_list:
        child_data = child.json()
        child_data["children"] = []
        if child.children:
            child_data["isParent"] = True
        for son in child.children:
            son_data = son.json()
            child_data["children"].append(son_data)
        ret.append(child_data)
    return {"code": 0, "message": "请求权限数据成功", "data": ret}

新增部门

1、新增表格头部点击元素

html
<script type="text/html" id="department-toolbar">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" lay-event="department-toolbar-add">
      新增部门
    </button>
  </div>
</script>

2、处理头部点击事件

处理头部点击事件,打开新增表单

javascript
treeTable.on("toolbar(department-treeTable)", function (obj) {
  if (obj.event === "department-toolbar-add") {
    $("#department-form")[0].reset();
    layer.open({
      type: 1,
      shade: false,
      content: $("#department-form"),
      area: ["50%", "80%"],
    });
    form.render($("#department-form"));
  }
});

3、新增页面表单

html
<form
  class="layui-form"
  lay-filter="department-form"
  id="department-form"
  action=""
  style="padding: 15px; display: none"
>
  <div class="layui-form-item">
    <label class="layui-form-label">ID</label>
    <div class="layui-input-block">
      <input
        type="text"
        name="id"
        value="0"
        lay-verify="required"
        autocomplete="off"
        class="layui-input"
        disabled
      />
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">部门名</label>
    <div class="layui-input-block">
      <input
        type="text"
        name="name"
        placeholder="请输入部门名"
        lay-verify="required"
        autocomplete="off"
        class="layui-input"
      />
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">负责人</label>
    <div class="layui-input-block">
      <input
        type="text"
        name="leader"
        placeholder="请输入负责人"
        lay-verify="required"
        autocomplete="off"
        class="layui-input"
      />
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">状态</label>
    <div class="layui-input-block">
      <input
        type="checkbox"
        name="enable"
        lay-skin="switch"
        autocomplete="off"
        checked
        title="启用|禁用"
        class="layui-input"
      />
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">上级部门ID</label>
    <div class="layui-input-block">
      <input
        type="text"
        name="pid"
        placeholder="请输入上级部门id"
        autocomplete="off"
        class="layui-input"
      />
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-input-block">
      <button
        type="submit"
        class="layui-btn"
        lay-submit
        lay-filter="department-form-btn"
      >
        立即提交
      </button>
      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
    </div>
  </div>
</form>

4、监听表单提交

javascript
form.on("submit(department-form-btn)", function (data) {
  var field = data.field;

  data.field.enable = data.field.enable === "on";

  field.id = null;
  method = "POST";
  url = "/api/v1/department";

  $.ajax({
    url: url,
    type: method,
    contentType: "application/json",
    data: JSON.stringify(field),
    success: function (res) {
      if (!res.code) {
        layer.closeAll();
        treeTable.reloadData("department-treeTable");
      }
    },
  });
  return false;
});

6、后端实现新增操作

python
@department_api.post("/department")
def create_department():
    data = request.get_json()
    if data.get("id"):
        del data["id"]
    department = DepartmentORM(**data)
    department.save()
    return {"code": 0, "msg": "新增部门成功"}

修改部门

1、添加表格行事件标签

html
<script type="text/html" id="department-tool">
  <div class="layui-btn-container">
    <button
      class="layui-btn layui-btn-sm layui-bg-blue"
      lay-event="department-tool-edit"
    >
      编辑
    </button>
    <button
      class="layui-btn layui-btn-sm layui-bg-red"
      lay-event="department-tool-del"
    >
      删除
    </button>
  </div>
</script>

2、监听表格栏点击事件

javascript
treeTable.on("tool(department-treeTable)", function (obj) {
  if (obj.event === "department-tool-edit") {
    form.val("department-form", obj.data);
    layer.open({
      type: 1,
      shade: false,
      content: $("#department-form"),
      area: ["50%", "80%"],
    });
  }
});

3、编辑操作

新增与编辑共用一张表单,共用同一个 ajax 请求。

javascript
form.on("submit(department-form-btn)", function (data) {
  var field = data.field;

  data.field.enable = data.field.enable === "on";

  field.id = null; 
  method = "POST"; 
  url = "/api/v1/department"; 

  let method, url; 
  if (field.id == 0) {

    field.id = null; 
    method = "POST"; 
    url = "/api/v1/department"; 
  } else {

    method = "PUT"; 
    url = `/api/v1/department/${field.id}`; 
  } 
  $.ajax({
    url: url,
    type: method,
    contentType: "application/json",
    data: JSON.stringify(field),
    success: function (res) {
      if (!res.code) {
        layer.closeAll();
        treeTable.reloadData("department-treeTable");
      }
    },
  });
  return false;
});

4、后端完成修改

python
@department_api.put("/department/<int:rid>")
def change_department(rid):
    data = request.get_json()
    del data["id"]

    department_obj = DepartmentORM.query.get(rid)
    for key, value in data.items():
        setattr(department_obj, key, value)
    department_obj.save()
    return {"code": 0, "msg": "修改部门成功"}

删除部门

javascript
treeTable.on("tool(department-treeTable)", function (obj) {
  if (obj.event === "department-tool-edit") {
    form.val("department-form", obj.data);
    layer.open({
      type: 1,
      shade: false,
      content: $("#department-form"),
      area: ["50%", "80%"],
    });
  } else if (obj.event === "department-tool-del") {
    $.ajax({
      url: `/api/v1/department/${obj.data.id}`,
      type: "DELETE",
      contentType: "application/json",
      success: function (res) {
        if (!res.code) {
          treeTable.reloadData("department-treeTable");
        }
      },
    });
  }
});

后端逻辑实现

python
@department_api.delete("/department/<int:rid>")
def del_department(rid):
    department_obj = DepartmentORM.query.get(rid)
    department_obj.delete()
    return {"code": 0, "msg": "删除删除成功"}