antDesgin + vue3 table组件二次封装

1.在hook文件下创建usePageReq.js,封装代码如下(代码是之前一个博主那看到的,忘记是那个了,根据我的需求稍作改动)

import { ref, reactive, toRefs, watch } from 'vue'
 
export const usePageReq = (api, otherParams) => {
    // 表格的loading(不需要可以删除)
    const tableLoading = ref(true)
    // 分页的页数和一页的大小
    const pageParams = reactive({
        PageNumber: 1,
        MaxResultCount: 15
    })
    const datas = ref([])
    const totalCount = ref()  //数据的总条数
    let apiOtherParams =ref({}) 
    const getPage = (serchParms) => {
        // 处理传过来的参数
        Object.keys(otherParams).forEach(key => {
            let targeParams = otherParams[key]
            if(typeof targeParams === 'object') {
                Object.assign(apiOtherParams.value, targeParams)
            } else {
                // 日期参数date的话,而且数组说明是dateRange,参数才分为start和end, date:[]
                if(key === 'date' && Array.isArray(targeParams)) {
                    apiOtherParams.value['start'] = targeParams[0]
                    apiOtherParams.value['end'] = targeParams[1]
                } else {
                    apiOtherParams.value[key] = targeParams
                }
            }
        })
        // 当页面有查询寻求时,传入的查询参数
        const realSerchParms = serchParms ? { ...serchParms } :''
        api({
        //请求参数,这里取决于你的接口需要什么参数
            ...pageParams, //分页
            ...apiOtherParams.value, // 请求时除了分页以外的参数
            ...realSerchParms // 查询参数
        }).then(res=> {
        // 这里接收你的请求结果,有什么数据需要获取都写在这里
            datas.value = res.items
            tableLoading.value=false
            totalCount.value=Number(res.totalCount)  //后端返回给我的总数是字符串,是数字类型的可以不转换
        })
    }
 

    watch(() =>otherParams, (newVal) => {
        if (newVal) {
            getPage()  
        }
    },  { immediate: true, deep: true })
 
    // 刷新表格再次请求
    const search = () => {
        window.scrollTo(0, 0)
        pageParams.PageNumber = 1
        getPage()
    }
 
// 对外面返回你的参数,想返回什么写什么
    return {
        datas,
        pageParams,
        getPage,
        search,
        totalCount,
        tableLoading
    }
}

2.table组件封装代码

<template>
  <a-table
        class="tableList"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data-source="datas"
        :pagination="false"
        :loading="tableLoading"
        size="small" 
      >
        <template #bodyCell="{ column,index,record }">
          <template v-if="column.key === 'index'">
            {{`${( pageParams.PageNumber - 1) * pageParams.MaxResultCount + index +1}`}}
        </template>
          <template v-if="column.key === 'action'">
            <slot name='tableBtns' :row='record'></slot>
            <a href="javascript:;" @click="del(record)" v-if="delBut" class="delBtn">删除</a>
        </template>
        </template>
      </a-table>
       <div class="paginationBox">
          <a-pagination
              size="small"
              :defaultPageSize="15"
              :page-size-options="pageSizeOptions"
              v-model:current="pageParams.PageNumber"
              :total="totalCount"
              :show-total="total => `共 ${totalCount} 条`"
              show-size-changer
              @change="change"
          />
    </div>
</template>

<script setup>
import { usePageReq } from '../../hook/usePageReq.js'
import { defineComponent, onMounted, reactive, ref,h } from 'vue'
import { message, Modal } from "ant-design-vue";
const props = defineProps({
  // 表格配置项
  columns: {
    type: Array,
    default: () => []
  }, 
// 是否展示删除按钮
  delBut:{
    type: Boolean,
    default: true
  },
// 删除接口
  delApi:{
     type: Function,
    default: () => {}
  },
  // 请求数据的接口
  api: {
    type: Function,
    default: () => {}
  },
  // 接口参数
  apiParams: {
    type: Object,
    default: () => {}
  },
  // 表格X轴的滚动距离
  scrollX: {
    type: Number,
    default: 2500
  },
  // 表格Y轴的滚动距离
  scrollY: {
    type: Number,
    default: 450
  },
})

const { datas, pageParams, getPage ,totalCount ,tableLoading} = usePageReq(props.api,props.apiParams)
const pageSizeOptions = ref(['15', '20', '30', '40', '50']);
const change = (cur,max)=>{
  if (pageParams.MaxResultCount!=max) {
      pageParams.PageNumber=1
      pageParams.MaxResultCount=max
  }else{
     pageParams.PageNumber=cur
  }
 getPage()
}
const del = async (params)=>{
  Modal.confirm({
    title: h("div", {}, "是否要删除【", [
      h("b", { style: "color: red" }, params.name),
      h("span", "】?"),
    ]),
    okText: "确定",
    cancelText: "取消",
    closable:true,
    onOk: () => {
      props.delApi({ id: params.id })
        .then((res) => {
            message.success("删除成功!")
              pageParams.PageNumber =
                datas.value.length == 1 && pageParams.PageNumber != 1
                  ? pageParams.PageNumber - 1
                  : pageParams.PageNumber;
              getPage();
        })
        .catch((err) => {
          console.log(err);
        });
    },
  });
}
onMounted(()=>{
  // getPage()
})
defineExpose({
  datas,
  pageParams,
  getPage,
  totalCount
})
</script>

<style>

</style>

3.在组件中使用

<template>
  <div>
     <div class="search_box">
//查询组件
      <SearchItem
        :searchitem="searchitem"
        :submitFunc="submitFunc"
        ref="search"
      ></SearchItem>
    </div>
     <div class="table_box">
       <div class="button_box">
        <a-button
          class="box_right_header_btn"
          type="primary"
          @click="creatformfunc('add')"
          ><plus-outlined />添加</a-button
        >
      </div>
    <tableCom :columns="columns" :api="getStore" :apiParams="otherParmas" ref="tableComRef" :delApi="delStore">
      <template #tableBtns="{ row }">
          <a href="javascript:;" @click="edit(row)">修改</a>
          <a-divider type="vertical" />
      </template>
    </tableCom>
     </div>
  </div>
</template>

<script setup>
import { usePageReq } from '@/hook/usePageReq.js'
import { getStore,getOutin,delOutin,delStore} from "@/api/repairsManage";
import { defineComponent, reactive,ref,h } from "vue";
import tableCom from "@/components/table/index.vue";
import { useHandleData } from "@/hook/useHandleData.js"
import SearchItem from "@/components/SearchItem/index.vue";
import { message, Modal } from "ant-design-vue";
import dayjs from "dayjs";
const columns = ref([
  {
    title: "序号",
    dataIndex: "index",
    key: "index",
    align: "center",
    width: 60,
  },
 {
    title: "仓库名称",
    dataIndex: "name", 
    key: "name",
    width: 250,
    ellipsis:true,
  },
  {
    title: "操作",
    key: "action",
    align: "center",
    fixed: "right",
    width: 120,
  },
]);
const otherParmas = ref({}); // 刚开始请求时,除了分页之外的其他的接口
const tableComRef = ref()
const searchParams = ref() //搜索参数
const searchitem = ref([
  {
    type: "input",
    label: "仓库名称",
    val: "",
    selectList: [],
    placeholder: "请输入仓库名称",
    queryName: "name",
    allowClear: null,
    rules: [],
  },
]);
const submitFunc =async (from)=>{ //点击查询按钮
  searchParams.value = {
    SearchText: from.name,
  };
    tableComRef.value.pageParams.PageNumber=1
  tableComRef.value.getPage(searchParams.value) 
}
const edit = (row)=>{
    console.log(row);
}

</script>

<style>
</style>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值