80 lines
2.7 KiB
Vue
80 lines
2.7 KiB
Vue
<script setup lang="ts">
|
|
/**
|
|
* 通用分页条(列表页共用)
|
|
*
|
|
* 用法:
|
|
* ```vue
|
|
* <DataPager :page="page" :page-size="pageSize" :total="total" :loading="loading"
|
|
* unit="条" @update:page="load" @update:page-size="onPageSize" />
|
|
* ```
|
|
*
|
|
* 约定:页码从 **1** 开始;页面收到 `update:page` 后自己去取数据。
|
|
* `update:page-size` 时本组件会**同时发一次 `update:page`(1)**,页面两件事都要处理
|
|
* (或只处理 pageSize 然后自己重新 load(1))。
|
|
*/
|
|
import { computed, ref } from 'vue';
|
|
|
|
const props = withDefaults(defineProps<{
|
|
page: number;
|
|
pageSize: number;
|
|
total: number;
|
|
/** 可选的每页条数 */
|
|
pageSizes?: number[];
|
|
/** 单位(条 / 台 / 个) */
|
|
unit?: string;
|
|
/** 加载中:禁用所有按钮 */
|
|
loading?: boolean;
|
|
}>(), {
|
|
pageSizes: () => [ 10, 20, 50, 100 ],
|
|
unit: '条',
|
|
loading: false,
|
|
});
|
|
|
|
const emit = defineEmits<{
|
|
(e: 'update:page', value: number): void;
|
|
(e: 'update:pageSize', value: number): void;
|
|
}>();
|
|
|
|
const pages = computed(() => Math.max(Math.ceil(props.total / Math.max(props.pageSize, 1)), 1));
|
|
const jump = ref('');
|
|
|
|
function go(target: number) {
|
|
if (props.loading) return;
|
|
const clamped = Math.min(Math.max(Math.trunc(target), 1), pages.value);
|
|
if (clamped !== props.page) emit('update:page', clamped);
|
|
}
|
|
|
|
function onPageSizeChange(event: Event) {
|
|
const value = Number((event.target as HTMLSelectElement).value);
|
|
if (!Number.isFinite(value) || value <= 0 || value === props.pageSize) return;
|
|
|
|
emit('update:pageSize', value);
|
|
emit('update:page', 1);
|
|
}
|
|
|
|
function onJump() {
|
|
const value = Number(jump.value);
|
|
jump.value = '';
|
|
if (Number.isFinite(value) && value > 0) go(value);
|
|
}
|
|
</script>
|
|
|
|
<template>
|
|
<div class="pager">
|
|
<span class="hint">共 {{ total }} {{ unit }}</span>
|
|
|
|
<button class="btn btn-ghost btn-sm" :disabled="loading || page <= 1" @click="go(1)">首页</button>
|
|
<button class="btn btn-ghost btn-sm" :disabled="loading || page <= 1" @click="go(page - 1)">上一页</button>
|
|
<span class="hint pager-pos">{{ page }} / {{ pages }}</span>
|
|
<button class="btn btn-ghost btn-sm" :disabled="loading || page >= pages" @click="go(page + 1)">下一页</button>
|
|
<button class="btn btn-ghost btn-sm" :disabled="loading || page >= pages" @click="go(pages)">末页</button>
|
|
|
|
<select class="pager-select" :value="pageSize" :disabled="loading" @change="onPageSizeChange">
|
|
<option v-for="size in pageSizes" :key="size" :value="size">{{ size }} 条/页</option>
|
|
</select>
|
|
|
|
<input v-model="jump" class="pager-jump" placeholder="跳页" inputmode="numeric"
|
|
:disabled="loading" @keyup.enter="onJump" />
|
|
</div>
|
|
</template>
|