vue3+antd的table小组件

antdtable组件支持增加搜索栏配置。增加按钮等操作。

闲话少叙,上代码

<!-- 更多与收起详见用户管理页面 -->
<template>
  <div class="c-data-table">
    <a-spin :spinning="spinning">
      <a-card :title="title" :bordered="false">
        <div class="dt-search" v-if="$slots.search || $slots.searchmore">
          <!--  -->
          <a-form
            ref="searchform"
            size="mini"
            class="dt-search-form-inline"
            layout="inline"
            :model="searchParams"
            @submit.prevent="search({ _fromBar: true, _begin: 0 })"
          >
            <div v-if="showmore">
              <div class="formSearchLittle">
                <slot name="search" />
              </div>
            </div>
            <div v-else>
              <div class="">
                <slot name="searchmore" />
              </div>
            </div>
            <button type="submit" style="display: none;"></button>
          </a-form>
        </div>
        <div class="dt-toolbar" v-if="$slots.toolbar">
          <slot name="toolbar" />
        </div>
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :pagination="false"
          :bordered="bordered"
          rowKey="id"
        >
        </a-table>
        <a-config-provider :locale="locale" v-if="pageable">
          <a-pagination
            show-size-changer
            v-model:current="current"
            v-model:pageSize="pageSize"
            :total="total"
            :showQuickJumper="true"
            @showSizeChange="onShowSizeChange"
            @change="onChange"
          >
          </a-pagination>
        </a-config-provider>
      </a-card>
    </a-spin>
  </div>
</template>
<script>
import { defineComponent, ref, watch, getCurrentInstance } from "vue";
import zhCN from "ant-design-vue/lib/locale-provider/zh_CN";
import { message } from "ant-design-vue";
import { useForm } from "@ant-design-vue/use";
export default defineComponent({
  name: "c-data-table",
  props: {
    //是否显示边框
    bordered: {
      type: Boolean,
      default: false,
    },
    // 请求的返回渲染参数
    resultKey: {
      type: String,
      default: "data",
    },
    // 行
    columns: Array,
    //请求地址
    serverId: String,
    //搜索请求
    searchParams: {
      type: Object,
      default: () => ({}),
    },
    title: String,
    // 是否显示分页
    pageable: {
      type: Boolean,
      default: true,
    },
  },
  setup() {
    let { proxy } = getCurrentInstance();
    const dataSource = ref([]);
    // const searchParams = reactive({ name: "" });
    const { resetFields } = useForm(proxy.$props.searchParams, {});
    const spinning = ref(false);
    const pageSize = ref(20);
    const current = ref(1);
    const total = ref(0);
    const onShowSizeChange = (current, pageSize) => {
      console.log(current, pageSize);
    };
    const onChange = (pageNumber) => {
      console.log("Page: ", pageNumber);
      search();
    };

    // 页面搜索
    const search = (params = {}, fn = (rows) => rows) => {
      const { _begin } = params;
      console.log(proxy, fn);
      if (_begin >= 0) {
        current.value = _begin + 1;
      }
      const defaultParams = {
        pageNum: current.value,
        pageSize: pageSize.value,
        ...proxy.$props.searchParams,
      };
      spinning.value = true;
      return proxy.axios
        .get(proxy.$props.serverId, {
          params: { ...defaultParams },
        })
        .then((response) => {
          if (response.data.status == 1) {
            if (proxy.$props.pageable) {
              total.value = response.data.pageInfo.totalCount;
            }
            dataSource.value = response.data.data;
          } else {
            message.error("操作失败");
          }
        })
        .catch((error) => {
          console.log(error);
          message.error("接口异常");
        })
        .finally(() => {
          spinning.value = false;
        });
    };

    //展开与收起
    const showmore = ref(true);
    const toogleShow = () => {
      showmore.value = !showmore.value;
    };
    watch(pageSize, () => {
      search();
    });
    return {
      onShowSizeChange,
      dataSource,
      onChange,
      locale: zhCN,
      total,
      pageSize,
      current,
      search,
      spinning,
      resetFields,
      showmore,
      toogleShow,
    };
  },
});
</script>
<style lang="scss">
.c-data-table {
  .ant-table-thead > tr > th {
    background-color: #1890ff;
    line-height: 14px;
    color: #fff;
    border-bottom: 5px solid #fff;
  }

  .ant-table-tbody > tr > td {
    line-height: 5px;
    background-color: #f0f8ff;
    border-bottom: 5px solid #fff;
  }

  .ant-table-tbody
    > tr:hover:not(.ant-table-expanded-row):not(.ant-table-row-selected)
    > td {
    background-color: #ddebff !important;
  }
  .ant-pagination {
    margin-top: 1em;
  }
  .dt-search {
    box-sizing: border-box;
    padding: 8px 0 5px;
    .dt-search-form-inline {
      .ant-form-item {
        margin-bottom: 5px;
        &:last-child {
          margin-right: 0;
        }
      }
    }
    .formSearchLookMore {
      display: inline-block;
      position: relative;
      top: 4px;
    }
    .formSearchLittle {
      display: inline-block;
      margin-right: 20px;
    }
  }
  .dt-search {
    .ant-btn {
      min-width: 79px;
      margin-right: 10px;
      font-size: 14px;
    }
  }
  .ant-card-body {
    padding: 0px 24px 24px;
  }
  .btnbox {
    a {
      margin-right: 20px;
    }
  }
}
.dt-toolbar {
  box-sizing: border-box;
  padding: 8px 0;
  .ant-btn {
    min-width: 79px;
    margin-right: 10px;
    font-size: 13px;
  }
}
</style>

下边我们看一下这个组件的使用方法
使用的时候请放开所有注释

<!---本页面注释建议不要随便动!!!!!!!!!!!!!--->
<template>
  <div>
    <a-spin :spinning="loading">
      <c-data-table
        :columns="columns"
        :title="'用户管理'"
        :searchParams="searchParams"
        ref="RefChilde"
        serverId="/apis/users"
        resultKey="data"
      >
        <template v-slot:search>
          <a-form-item label="用户名">
            <a-input v-model:value="searchParams.username" />
          </a-form-item>
          <a-form-item label="部门">
            <a-input v-model:value="searchParams.deptName" />
          </a-form-item>
          <span class="formSearchLookMore">
            <a-button type="primary" class="search" @click="gosearch()">
              <template #icon>
                <SearchOutlined />
                查询
              </template>
            </a-button>
            <a-button type="default" class="reset" @click="reset()">
              <template #icon>
                <ReloadOutlined />
                重置
              </template>
            </a-button>
            <!-- <a href="javascript:;" @click="toogleShowMore">展开<DownOutlined /></a> -->
          </span>
        </template>
        <!-- <template v-slot:searchmore>
        <a-form-item label="用户名:">
          <a-input v-model:value="searchParams.username" />
        </a-form-item>
        <a-form-item label="密码:">
          <a-input v-model:value="searchParams.deptName" />
        </a-form-item>
        <a-form-item label="用户名:">
          <a-input v-model:value="searchParams.name1" />
        </a-form-item>
        <a-form-item label="密码:">
          <a-input v-model:value="searchParams.pass1" />
        </a-form-item>
        <a-form-item label="用户名:">
          <a-input v-model:value="searchParams.name2" />
        </a-form-item>
        <a-form-item label="密码:">
          <a-input v-model:value="searchParams.pass2" />
        </a-form-item>
        <a-button type="primary" class="search" @click="gosearch()">
          <template #icon>
            <SearchOutlined />
            查询
          </template>
        </a-button>
        <a-button type="default" class="reset" @click="resetFields">
          <template #icon>
            <ReloadOutlined />
            重置
          </template>
        </a-button>
        <a href="javascript:;" @click="toogleShowMore">收起<UpOutlined /></a>
      </template> -->
      </c-data-table>
    </a-spin>
  </div>
</template>
<script>
import {
  defineComponent,
  reactive,
  ref,
  getCurrentInstance,
  onMounted,
} from "vue";
import zhCN from "ant-design-vue/lib/locale-provider/zh_CN";
import { SearchOutlined, ReloadOutlined } from "@ant-design/icons-vue";
import { Modal, message } from "ant-design-vue";
import CDataTable from "../../../../commons/CDataTable";
import { fmtDict } from "../../../../commons/common";
import { gender, status } from "../../../../commons/publicArray";
import _ from "lodash";
export default defineComponent({
  components: {
    [CDataTable.name]: CDataTable,
    SearchOutlined,
    ReloadOutlined,
  },
  setup() {
    const columns = [
      {
        title: "用户名",
        dataIndex: "username",
        key: "username",
      },
      {
        title: "性别",
        dataIndex: "gender",
        customRender: ({ text }) => {
          return <div>{fmtDict(text, gender)}</div>;
        },
      },
      {
        title: "手机号",
        dataIndex: "phone",
        key: "phone",
        ellipsis: true,
      },
      {
        title: "邮箱",
        dataIndex: "email",
        key: "email",
        ellipsis: true,
      },
      {
        title: "部门",
        dataIndex: "deptName",
        key: "deptName",
        ellipsis: true,
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
        key: "createTime",
        ellipsis: true,
      },
      {
        title: "更新时间",
        dataIndex: "updateTime",
        key: "updateTime",
        ellipsis: true,
      },
      {
        title: "用户状态",
        dataIndex: "status",
        customRender: ({ text }) => {
          return <div>{fmtDict(text, status)}</div>;
        },
      },
      {
        title: "操作",
        width: "220px",
        customRender: ({ text, index }) => {
          if (text.status == "FROZEN") {
            return (
              <div class="btnbox">
                <a href="javascript:;" onClick={() => lookMore(text, index)}>
                  角色分配
                </a>
                <a href="javascript:;" onClick={() => unblock(text, index)}>
                  解冻
                </a>
              </div>
            );
          } else {
            return (
              <div class="btnbox">
                <a href="javascript:;" onClick={() => lookMore(text, index)}>
                  角色分配
                </a>
                <a href="javascript:;" onClick={() => block(text, index)}>
                  冻结
                </a>
              </div>
            );
          }
        },
      },
    ];
    let { proxy } = getCurrentInstance();
    //搜索数据
    const searchParams = reactive({
      username: "",
      deptName: "",
    });
    //loading加载
    const loading = ref(false);
    //弹框显示与隐藏
    const visible = ref(false);
    const RefChilde = ref(null);
    //角色弹框title
    const title = ref("");
    //用于存储userid
    const userId = ref();
    //用户分配角色
    const targetKeys = ref([]);
    const selectedKeys = ref([]);
    const mockData = ref([]);
    const handleChange = (nextTargetKeys, direction, moveKeys) => {
      console.log("nextTargetKeys", nextTargetKeys);
      console.log("direction: ", direction);
      console.log("moveKeys: ", moveKeys);
      if (direction == "right") {
        //绑定角色
        proxy.axios
          .post("/apis/users/" + userId.value + "/bindRole", {
            roleIds: moveKeys,
          })
          .then((res) => {
            if (res.data.status == 1) {
              message.success("分配成功");
              targetKeys.value = nextTargetKeys;
            } else {
              message.error("分配失败");
            }
          });
      } else {
        //移出角色
        proxy.axios
          .post("/apis/users/" + userId.value + "/removeRole", {
            roleIds: moveKeys,
          })
          .then((res) => {
            if (res.data.status == 1) {
              message.success("移除成功");
              targetKeys.value = nextTargetKeys;
            } else {
              message.error("移除失败");
            }
          });
      }
    };

    const handleSelectChange = (sourceSelectedKeys, targetSelectedKeys) => {
      selectedKeys.value = [...sourceSelectedKeys, ...targetSelectedKeys];
    };

    //调用子组件的查询方法
    const gosearch = () => {
      RefChilde.value.search({ _fromBar: true, _begin: 0 });
    };
    //掉用子组件的重置方法
    const reset = () => {
      RefChilde.value.resetFields();
    };
    //给用户绑定角色拉起弹框
    const lookMore = (text, index) => {
      console.log(text, index);
      loading.value = true;
      title.value = "为 " + text.username + " 赋予角色";
      userId.value = text.id;
      proxy.axios
        .get("/apis/users/" + text.id + "/roles")
        .then((res) => {
          mockData.value = res.data.data.assigned.concat(
            res.data.data.available
          );
          _.forEach(res.data.data.assigned, (item) => {
            targetKeys.value.push(item.id);
          });
          visible.value = true;
        })
        .catch(() => {
          message.error("获取失败");
        })
        .finally(() => {
          loading.value = false;
        });
    };
    //冻结
    const block = (item, index) => {
      console.log(item, index);
      Modal.warning({
        title: "请确认是否对用户" + item.name + "进行冻结操作",
        okText: "确认", // 设置按钮内容,默认为 OK
        onOk: () => {
          // 点击确认后的回调
          proxy.axios
            .patch("/apis/users/" + item.id + "/freeze")
            .then((res) => {
              if (res.data.status == 1) {
                message.success("冻结成功");
                gosearch();
              } else {
                message.error("冻结失败");
              }
            })
            .catch((error) => {
              message.error(error);
            });
        },
      });
    };
    //解冻
    const unblock = (item, index) => {
      console.log(item, index);
      Modal.warning({
        title: "请确认是否对用户" + item.name + "进行解冻操作",
        okText: "确认", // 设置按钮内容,默认为 OK
        onOk: () => {
          // 点击确认后的回调
          proxy.axios
            .patch("/apis/users/" + item.id + "/unfreeze")
            .then((res) => {
              if (res.data.status == 1) {
                message.success("解冻成功");
                gosearch();
              } else {
                message.error("解冻失败");
              }
            })
            .catch((error) => {
              message.error(error);
            });
        },
      });
    };
    //展开与收起切换
    // const toogleShowMore = () => {
    //   RefChilde.value.toogleShow();
    // };
    onMounted(() => {
      gosearch();
    });
    return {
      columns,
      lookMore,
      searchParams,
      gosearch,
      reset,
      RefChilde,
      // toogleShowMore,
      block,
      unblock,
      loading,
      visible,
      title,

      mockData,
      targetKeys,
      selectedKeys,
      handleChange,
      handleSelectChange,
      locale: zhCN,
    };
  },
});
</script>

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,711评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,079评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,194评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,089评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,197评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,306评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,338评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,119评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,541评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,846评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,014评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,694评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,322评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,026评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,257评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,863评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,895评论 2 351

推荐阅读更多精彩内容