• vue3+antdv 表格封装


    tool.ts

    
    /**生成唯一ID */
    let _idCounter = 0;
    export function generateUniqueID() {
      var ts = new Date().getTime().toString();
      var parts = ts.split("").reverse();
      var id = "";
      for (var i = 0; i < 5; ++i) {
        var index = Math.floor(Math.random() * parts.length);
        id += parts[index];
      }
      id += (++_idCounter);
      return id;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    <template>
        <div class="table-box" :id="props.id">
            <Table class="table-content" bordered :rowKey="(record) => record[props.rowKey]" :row-selection="rowSelection"
                :pagination="false" :scroll="{ y: props.scrollY || state.scrollY }" :columns="props.columns"
                :loading="state.loading" :data-source="state.tableData" :size="props.size" v-bind="$attrs">
                <template v-slot:headerCell="{ column }">
                    <p class="table-title" :class="tableTitleClass(props.columns)">{{ column.title }}p>
                template>
                <template v-if="props.isCustomEmpty" v-slot:emptyText>
                    <slot name="emptyText">slot>
                template>
                <template v-slot:bodyCell="{ column, record, index }">
                    <template v-for="slotName of props.slots">
                        <slot v-if="slotName === column?.dataIndex && column?.dataIndex !== 'index'" :name="slotName"
                            :column="column" :record="record" :index="index">slot>
                    template>
                    <span v-if="column && column?.dataIndex === 'index'">
                        {{ getRowIndex(index) }}
                    span>
                    <span
                        v-if="column && column?.dataIndex !== 'index' && !props?.slots?.includes(column.dataIndex as string)">{{
                            parseDefaultValue(record, column.dataIndex as string)
                        }}span>
                template>
            Table>
            <a-pagination v-if="props.isPagination" v-model:current="state.pagination.current"
                v-model:page-size="state.pagination.pageSize" :total="state.pagination.total"
                :showQuickJumper="state.pagination.showQuickJumper" :showSizeChanger="state.pagination.showSizeChanger"
                @change="state.pagination.onChange" :show-total="state.pagination.showTotal"
                :position="state.pagination.position" :size="props.size" />
        div>
    template>
    <script lang="ts" setup>
    import { Table, TablePaginationConfig } from "ant-design-vue";
    import { SizeType } from "ant-design-vue/lib/config-provider";
    import { reactive, computed, watch, nextTick, onUnmounted } from "vue"
    import request from "@/lib/request";
    import { AxiosRequestConfig } from "axios"
    import _ from 'lodash'
    import { generateUniqueID } from "@/lib/tool";
    const props = withDefaults(defineProps<{
        columns: any[];
        pagination?: false | TablePaginationConfig;
        dataSource?: any[];
        slots?: string[];
        scrollY?: number | 'auto';
        rowKey?: string;
        url?: string;
        baseURL?: string;
        reqMethods?: string;
        reqHeaders?: object;
        query?: object;
        parseTableData?: Function;
        isPagination?: boolean;
        defaultLoad?: boolean;
        pageParams?: any;
        pageNo?: string | number;
        pageSize?: string | number;
        isSelected?: boolean;
        size?: SizeType;
        updateLoading?: Function;
        isCustomEmpty?: boolean;
        isClearSelectKeys?: boolean;
        currentKeys?: string[];
        currentKeysTable?: any[]
        id?: string
    }>(), {
        defaultLoad: true,
        pagination: false,
        isPagination: true,
        isSelected: true,
        size: 'small',
        isCustomEmpty: false,
        reqMethods: "POST",
        parseTableData: ({ data, code }: any) => {
            if (code == 200) {
                return { data: data.data, total: data.totalCount };
            }
            return {};
        },
        rowKey: 'id',
        id:'BaseTable'+generateUniqueID(),
        isClearSelectKeys: true
    });
    
    const {
        baseURL = window.APP_CONFIG.baseUrl,
        reqHeaders = {},
        pageParams = {
            pageNo: 1,
            pageSize: 10,
        },
    } = props
    interface TypeState {
        loading: boolean;
        tableData?: any[];
        pagination: TablePaginationConfig;
        selectedVlanIds: number[] | string[];
        scrollY: number | 'auto';
        tableHeight: string;
        selectedRows: any[];
    }
    const state: TypeState = reactive({
        loading: false,
        tableData: props.dataSource,
        pagination: {
            current: pageParams.pageNo,
            pageSize: pageParams.pageSize,
            total: 0,
            showSizeChanger: true,
            showQuickJumper: true,
            position: ["bottomCenter"],
            showTotal: (total) => `${total}`, // 展示总共有几条数据
            onChange: pageChange
        },
        selectedVlanIds: [] as string[] | number[],
        selectedRows: [] as any[],
        scrollY: 0,
        tableHeight: `calc(100% - 56px)`
    })
    function pageChange(page: number, pageSize: number) {
        currentChange(page)
        pageSize != state.pagination.pageSize && sizeChange(pageSize)
    }
    
    const $emit = defineEmits(['currentChange', 'sizeChange', 'onData', 'selectChange', 'tableChange']); // 父组件的触发事件
    async function getData() {
        if (!props.url) return;
        let params: AxiosRequestConfig = {
            baseURL: baseURL,
            url: props.url,
            method: props.reqMethods,
            headers: reqHeaders,
        };
        const page = {
            pageNo: state.pagination.current,
            pageSize: state.pagination.pageSize,
        }
        if (props.reqMethods === "GET") {
            params = {
                ...params,
                params: props.isPagination ? { ...props.query, ...page } : props.query,
            };
        } else {
            params = {
                ...params,
                data: props.isPagination ? { ...props.query, ...page } : props.query,
            };
        }
        try {
            if (props?.updateLoading) {
                props.updateLoading(true)
            } else {
                state.loading = true;
            }
            let dataS = await request(params);
            if (dataS) {
                let { data, total } = props.parseTableData(dataS);
                if (props?.isClearSelectKeys) {
                    onSelectChange([], [])
                }
                if (props?.currentKeys?.length) {
                    onSelectChange(props?.currentKeys, props?.currentKeysTable)
                }
                state.tableData = data;
                state.pagination.total = total;
                $emit("onData", data);
            }
        } catch (error) {
            console.log(error);
        } finally {
            if (props?.updateLoading) {
                props.updateLoading(false)
            } else {
                state.loading = false;
            }
        }
    }
    function refresh() {
        if (props.isPagination) {
            currentChange(1);
        } else {
            getData();
        }
    }
    function currentChange(val: number) {
        state.pagination.current = val;
        getData();
    }
    function sizeChange(val: number) {
        state.pagination.pageSize = val;
        $emit("sizeChange", val);
        currentChange(1);
    }
    const onSelectChange = (changeAbleRowKeys: any[], selectedRows: any) => {
        state.selectedVlanIds = changeAbleRowKeys;
        state.selectedRows = selectedRows;
        $emit('selectChange', changeAbleRowKeys, selectedRows)
    };
    const onSelect = (record: any, selected: any, _selectedRows: any) => {
        let arr = state.selectedVlanIds as any[];
        if (selected) {
            // onSelectChange(selectedRows?.map((e: any) => e[props.rowKey]), selectedRows)
            arr.push(record[props.rowKey] as string)
            state.selectedRows.push(record)
            onSelectChange(state.selectedVlanIds, state.selectedRows)
        } else {
            const arrI = arr.findIndex((e) => e === record[props.rowKey])
            const rowI = state.selectedRows.findIndex((e) => e[props.rowKey] === record[props.rowKey])
            state.selectedRows.splice(rowI, 1)
            arr.splice(arrI, 1)
            onSelectChange(arr, state.selectedRows)
        }
    }
    
    const onSelectAll = (selected: any, _selectedRows: any, _changeRows: any) => {
        if (selected) {
            if (state.tableData) {
                onSelectChange(state.tableData?.map((e: any) => e[props.rowKey]), state.tableData)
            }
        } else {
            onSelectChange([], [])
        }
    }
    
    const rowSelection = computed(() => {
        let result: {} | undefined = undefined
        if (props.isSelected) {
            result = {
                selectedRowKeys: state.selectedVlanIds,
                // onChange: onSelectChange,
                onSelectAll: onSelectAll,
                hideDefaultSelections: true,
                onSelect: onSelect,
            }
        }
        return result;
    });
    props.defaultLoad && refresh()
    const parseDefaultValue = (record: Record<string, any>, dataIndex: string) => {
        const dataIndexs = dataIndex.split(".");
        let result = record;
        dataIndexs.forEach((element) => {
            if (result) {
                result = result[element];
            }
        });
        if (result == null) {
            return "--";
        }
        return result;
    };
    function getRowIndex(index: number) {
        const pageParams = {
            pageNo: state?.pagination?.current || 0,
            pageSize: state?.pagination?.pageSize,
        }
        if (pageParams && pageParams.pageSize) {
            return (
                pageParams.pageSize * (pageParams?.pageNo - 1) +
                index +
                1
            );
        }
        return index + 1;
    }
    function tableTitleClass(column: any) {
        return `${column?.isRequired ? 'is-required' : ''}`
    }
    function getTableData() {
        return state.tableData
    }
    function getSelectKeys() {
        return state.selectedVlanIds
    }
    const doLayout = _.debounce(function () {
        nextTick(() => {
            const tableMain = (document.querySelector(`#${props.id} .table-content`) as HTMLDivElement)?.offsetHeight
            const headerH = (document.querySelector(`#${props.id} .ant-table-header`) as HTMLDivElement)?.offsetHeight
            state.scrollY = tableMain - headerH
        })
    }, 200)
    doLayout()
    window.addEventListener("resize", doLayout);
    onUnmounted(() => {
        window.removeEventListener('resize', doLayout)
    })
    watch(
        () => props.isPagination,
        (val) => {
            nextTick(() => {
                const paginationH = (document.querySelector(`#${props.id} .ant-pagination`) as HTMLDivElement)?.offsetHeight
                state.tableHeight = val ? `calc(100% - ${paginationH}px)` : `100%`
            })
        },
        { immediate: true }
    );
    watch(
        () => props.dataSource,
        (val) => {
            state.tableData = val
        },
        { immediate: true, deep: true }
    );
    watch(
        () => state.tableData,
        (val) => {
            $emit('tableChange', val)
            doLayout()
        },
        { immediate: true }
    );
    defineExpose({
        refresh,
        getTableData,
        doLayout,
        onSelectChange,
        getSelectKeys
    })
    script>
    
    <style scoped lang="scss">
    $bg-color: #fff;
    
    .table-box {
        height: 100%;
        background-color: $bg-color;
    
        .table-content {
            height: v-bind("state.tableHeight");
            overflow: auto;
        }
    
        :deep(.ant-pagination) {
            padding: 12px;
            display: flex;
            justify-content: center;
            background-color: $bg-color;
        }
    }
    
    
    .is-required {
        &:before {
            content: '*';
            color: red
        }
    }
    
    .table-title {
        white-space: break-spaces;
    }
    style>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
  • 相关阅读:
    .Net 7里的函数.Ctor和.CCtor是干啥用的呢?你知道吗
    [附源码]java毕业设计某互联网公司人力资源管理系统
    【科普向】5G核心网架构和关键技术
    源码编译Qt 5.15.9+msvc2019
    从零开始:PRD产品需求文档怎么写
    华为OD机试真题 Java 实现【阿里巴巴找黄金宝箱(II)】【2023 B卷 100分】,附详细解题思路
    Jmeter性能测试指南
    小满nestjs(第七章 RESTful 风格设计)
    【IP地址介绍】
    计算机毕业设计ssm校园疫情防控系统jt87q系统+程序+源码+lw+远程部署
  • 原文地址:https://blog.csdn.net/shibaweijin/article/details/134245655