feat: 添加瀑布流呈现商品卡和图片卡

This commit is contained in:
ah--desktop
2025-11-01 00:34:21 +08:00
parent dfc6de49e0
commit ecbc08c39b
11 changed files with 1513 additions and 2089 deletions
@@ -1,34 +1,22 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { ImageDTO, ImageVO } from '#/api/media/image/types';
import type { PageQueryDTO } from '#/types/common';
import type { ImageVO } from '#/api/media/image/types';
import { computed, ref } from 'vue';
import { ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import {
Button,
Divider,
Flex,
Image,
message,
Space,
Tag,
Upload,
} from 'ant-design-vue';
import { Button, Divider, Flex, message, Space, Upload } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
batchUploadImagesApi,
deleteImageApi,
getImagePageApi,
uploadImageApi,
} from '#/api/media/image';
import ImageEditModal from './components/ImageEditModal.vue';
import ImageGridView from './views/ImageGridView/index.vue';
import ImageListView from './views/ImageListView/index.vue';
defineOptions({ name: 'ImageRepository' });
// 创建图标组件
@@ -37,7 +25,6 @@ const GridIcon = createIconifyIcon('lucide:grid-3x3');
const ListIcon = createIconifyIcon('lucide:list');
// 响应式数据
const loading = ref(false);
const editModalVisible = ref(false);
const currentImageData = ref<ImageVO.Info | null>(null);
const uploadLoading = ref(false);
@@ -56,163 +43,19 @@ const imageCategoryOptions = [
{ label: 'Logo', value: 'logo' },
];
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
minWidth: 'auto',
title: '序号',
},
{
title: '预览',
minWidth: 'auto',
slots: { default: 'preview' },
},
{
field: 'filename',
title: '文件名',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
title: '分类',
minWidth: 'auto',
slots: { default: 'category' },
},
{
title: '标签',
minWidth: 'auto',
slots: { default: 'tags' },
},
{
field: 'remark',
title: '说明',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
field: 'uploadTime',
title: '上传时间',
minWidth: 'auto',
},
{
title: '操作',
minWidth: 'auto',
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
ajax: {
query: async ({ page }) => {
try {
loading.value = true;
const params: PageQueryDTO<ImageDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
filename: searchForm.value.filename || undefined,
category: searchForm.value.category || undefined,
},
};
const data = await getImagePageApi(params);
return {
items: data.records,
total: data.total,
};
} catch (error) {
console.error('获取图片列表失败:', error);
message.error('获取图片列表失败');
return {
items: [],
total: 0,
};
} finally {
loading.value = false;
}
},
},
},
};
// 搜索表单配置
const formOptions = computed(() => ({
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入文件名',
},
fieldName: 'filename',
label: '文件名',
},
{
component: 'Select',
componentProps: {
placeholder: '请选择图片分类',
options: imageCategoryOptions,
allowClear: true,
},
fieldName: 'category',
label: '图片分类',
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
// 列表视图和网格视图引用
const imageListViewRef = ref<null | { refreshTable: () => void }>(null);
const imageGridViewRef = ref<null | { refreshTable: () => void }>(null);
// 刷新表格数据
function refreshTable() {
if (gridApi) {
gridApi.reload();
if (viewMode.value === 'list' && imageListViewRef.value) {
imageListViewRef.value.refreshTable();
} else if (viewMode.value === 'grid' && imageGridViewRef.value) {
imageGridViewRef.value.refreshTable();
}
}
// 创建 VbenVxeGrid 实例
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '图片管理',
});
// 处理上传
const handleUpload = async (file: File) => {
uploadLoading.value = true;
@@ -271,6 +114,11 @@ const handleDelete = async (id: number) => {
}
};
// 处理列表视图删除
const handleListViewDelete = (id: number) => {
handleDelete(id);
};
// 处理编辑成功
const handleEditSuccess = () => {
refreshTable();
@@ -308,51 +156,6 @@ const uploadProps = {
}
},
};
// 获取分类标签颜色
const getCategoryColor = (category: string | undefined) => {
switch (category) {
case 'avatar': {
return 'green';
}
case 'image': {
return 'blue';
}
case 'logo': {
return 'purple';
}
default: {
return 'default';
}
}
};
// 获取分类显示文本
const getCategoryText = (category: string | undefined) => {
switch (category) {
case 'avatar': {
return '头像';
}
case 'image': {
return '普通图片';
}
case 'logo': {
return 'Logo';
}
default: {
return '未分类';
}
}
};
// 获取标签列表
const getTagList = (tags: string | undefined) => {
if (!tags) return [];
return tags
.split(',')
.map((tag) => tag.trim())
.filter(Boolean);
};
</script>
<template>
@@ -391,56 +194,20 @@ const getTagList = (tags: string | undefined) => {
</template>
<!-- 列表视图 -->
<Grid v-if="viewMode === 'list'" :loading="loading">
<!-- 预览列 -->
<template #preview="{ row }: { row: any }">
<Image
:src="row.url"
:alt="row.filename"
width="60"
height="60"
style="object-fit: cover; border-radius: 4px"
:preview="true"
/>
</template>
<!-- 分类列 -->
<template #category="{ row }: { row: any }">
<Tag :color="getCategoryColor(row.category)">
{{ getCategoryText(row.category) }}
</Tag>
</template>
<!-- 标签列 -->
<template #tags="{ row }: { row: any }">
<div v-if="row.tags" class="flex flex-wrap gap-1">
<Tag
v-for="tag in getTagList(row.tags)"
:key="tag"
size="small"
color="blue"
>
{{ tag }}
</Tag>
</div>
<span v-else class="text-gray-400">无标签</span>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleDownload(row)"> 下载 </Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row.id)">
删除
</Button>
</Space>
</template>
</Grid>
<ImageListView
v-if="viewMode === 'list'"
ref="imageListViewRef"
v-model:search-form="searchForm"
:category-options="imageCategoryOptions"
@edit="handleEdit"
@delete="handleListViewDelete"
@download="handleDownload"
/>
<!-- 网格视图 -->
<ImageGridView
v-else
ref="imageGridViewRef"
v-model:search-form="searchForm"
:category-options="imageCategoryOptions"
:upload-loading="uploadLoading"
@@ -449,14 +216,15 @@ const getTagList = (tags: string | undefined) => {
@download="handleDownload"
@preview="handlePreview"
/>
<!-- 编辑弹窗 -->
<ImageEditModal
v-model:open="editModalVisible"
:image-data="currentImageData"
@success="handleEditSuccess"
@cancel="editModalVisible = false"
/>
</Page>
<!-- 编辑弹窗 -->
<ImageEditModal
v-model:open="editModalVisible"
:image-data="currentImageData"
@success="handleEditSuccess"
@cancel="editModalVisible = false"
/>
</template>
<style scoped>
@@ -80,15 +80,19 @@ const getTagList = (tags: string | undefined) => {
</script>
<template>
<Card hoverable :body-style="{ padding: 0 }" class="image-card group">
<Card
hoverable
:body-style="{ padding: 0 }"
class="group border border-gray-200 transition-all duration-300 ease-out hover:-translate-y-1 hover:border-blue-500 hover:shadow-lg dark:border-gray-700"
>
<!-- 图片区域 -->
<div
class="relative aspect-square cursor-pointer overflow-hidden rounded-t-lg bg-gray-100 dark:bg-neutral-800"
class="relative cursor-pointer overflow-hidden rounded-t-lg bg-gray-100 dark:bg-neutral-800"
>
<Image
:src="image.url"
:alt="image.filename"
class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
class="w-full object-contain transition-transform duration-300 group-hover:scale-105"
:preview="true"
/>
@@ -172,20 +176,3 @@ const getTagList = (tags: string | undefined) => {
</div>
</Card>
</template>
<style scoped>
.image-card {
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
border: 1px solid var(--border-color);
}
.image-card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
border-color: var(--primary-color);
}
.image-card :deep(.ant-card-body) {
padding: 0 !important;
}
</style>
@@ -2,17 +2,18 @@
import type { ImageDTO, ImageVO } from '#/api/media/image/types';
import type { PageQueryDTO } from '#/types/common';
import { ref, watch } from 'vue';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { Waterfall } from 'vue-waterfall-plugin-next';
import 'vue-waterfall-plugin-next/dist/style.css';
import {
Button,
Card,
Col,
Empty,
Flex,
Form,
Input,
message,
Pagination,
Row,
Select,
Space,
Spin,
@@ -46,7 +47,14 @@ const loading = ref(false);
const imageList = ref<ImageVO.Info[]>([]);
const total = ref(0);
const current = ref(1);
const pageSize = ref(24); // 网格视图默认24个
const pageSize = ref(24); // 无限滚动默认每页24个
const hasMore = ref(true); // 是否还有更多数据
const scrollContainerRef = ref<HTMLElement | null>(null);
// 显示列表(只包含图片数据,不包含占位项)
const displayList = computed(() => {
return imageList.value;
});
// 本地搜索表单副本(用于 v-model)
const localSearchForm = ref({
@@ -64,8 +72,11 @@ watch(
) {
localSearchForm.value.filename = newForm.filename;
localSearchForm.value.category = newForm.category;
// 重置分页和列表
current.value = 1;
loadImageList();
imageList.value = [];
hasMore.value = true;
loadImageList(true);
}
},
{ deep: true },
@@ -86,7 +97,9 @@ watch(
);
// 加载图片列表
const loadImageList = async () => {
const loadImageList = async (reset = false) => {
if (loading.value || (!hasMore.value && !reset)) return;
loading.value = true;
try {
const params: PageQueryDTO<ImageDTO.Filters> = {
@@ -99,8 +112,22 @@ const loadImageList = async () => {
};
const response = await getImagePageApi(params);
imageList.value = response.records;
if (reset) {
imageList.value = response.records;
} else {
imageList.value.push(...response.records);
}
total.value = response.total;
// 判断是否还有更多数据
if (imageList.value.length >= response.total) {
hasMore.value = false;
} else {
current.value++;
hasMore.value = true;
}
} catch {
message.error('加载图片列表失败');
} finally {
@@ -111,7 +138,9 @@ const loadImageList = async () => {
// 搜索
const handleSearch = () => {
current.value = 1;
loadImageList();
imageList.value = [];
hasMore.value = true;
loadImageList(true);
};
// 重置
@@ -121,11 +150,16 @@ const handleReset = () => {
handleSearch();
};
// 分页变化
const handlePageChange = (page: number, size: number) => {
current.value = page;
pageSize.value = size;
loadImageList();
// 滚动监听
const handleScroll = () => {
const container = scrollContainerRef.value;
if (!container || loading.value || !hasMore.value) return;
const { scrollTop, scrollHeight, clientHeight } = container;
// 当滚动到距离底部 200px 时加载更多
if (scrollTop + clientHeight >= scrollHeight - 200) {
loadImageList();
}
};
// 事件处理
@@ -145,16 +179,40 @@ const handlePreview = (image: ImageVO.Info) => {
emit('preview', image);
};
// 初始化
loadImageList();
// 刷新列表
function refreshTable() {
handleSearch();
}
// 暴露方法
defineExpose({
refreshTable,
});
// 滚动监听
onMounted(() => {
loadImageList(true);
// 延迟绑定滚动事件,确保 DOM 已渲染
setTimeout(() => {
if (scrollContainerRef.value) {
scrollContainerRef.value.addEventListener('scroll', handleScroll);
}
}, 100);
});
onUnmounted(() => {
if (scrollContainerRef.value) {
scrollContainerRef.value.removeEventListener('scroll', handleScroll);
}
});
</script>
<template>
<div class="flex-col">
<div class="flex h-full flex-col">
<!-- 搜索区域 -->
<Card class="mb-4" :body-style="{ padding: '16px' }">
<Form :model="localSearchForm" layout="inline" class="w-full">
<div class="flex flex-wrap items-center gap-4">
<Flex class="w-full" justify="end" align="center" gap="4">
<Form.Item label="文件名" class="mb-0">
<Input
v-model:value="localSearchForm.filename"
@@ -189,57 +247,69 @@ loadImageList();
<div class="ml-auto text-sm text-gray-500 dark:text-gray-400">
共 {{ total }} 张图片
</div>
</div>
</Flex>
</Form>
</Card>
<!-- 网格内容 -->
<Card class="flex-1" :body-style="{ padding: '16px' }">
<Spin :spinning="loading">
<Row :gutter="[16, 16]">
<Col
v-for="image in imageList"
:key="image.id"
:xs="12"
:sm="8"
:md="6"
:lg="4"
:xl="3"
>
<ImageCard
:image="image"
@download="handleDownload"
@edit="handleEdit"
@delete="handleDelete"
@preview="handlePreview"
/>
</Col>
</Row>
<Card
class="flex flex-1 flex-col overflow-y-auto"
:body-style="{
padding: '16px',
display: 'flex',
flexDirection: 'column',
height: '100%',
}"
>
<Spin :spinning="loading && imageList.length === 0">
<!-- 空状态 -->
<div
v-if="!loading && imageList.length === 0"
class="py-16 text-center"
class="flex h-full items-center justify-center py-8"
>
<div class="mb-4 text-6xl">📷</div>
<div class="mb-2 text-lg text-gray-400">暂无图片数据</div>
<div class="text-sm text-gray-400">请上传图片或调整搜索条件</div>
<Empty />
</div>
<!-- 分页 -->
<div v-if="total > 0" class="mt-6 flex justify-center">
<Pagination
v-model:current="current"
v-model:page-size="pageSize"
:total="total"
:page-size-options="['12', '24', '48', '96']"
show-size-changer
show-quick-jumper
:show-total="
(total, range) => `第 ${range[0]}-${range[1]} 条,共 ${total} 条`
"
@change="handlePageChange"
/>
<!-- 瀑布流 -->
<div ref="scrollContainerRef" class="flex-1 overflow-auto">
<Waterfall
v-if="imageList.length > 0"
:list="displayList"
row-key="id"
:width="280"
:breakpoints="{
1600: { rowPerView: 5 },
1400: { rowPerView: 4 },
1200: { rowPerView: 4 },
992: { rowPerView: 3 },
768: { rowPerView: 2 },
500: { rowPerView: 1 },
}"
:gutter="16"
>
<template #default="{ item }">
<div class="w-full">
<ImageCard
:image="item"
@download="handleDownload"
@edit="handleEdit"
@delete="handleDelete"
@preview="handlePreview"
/>
</div>
</template>
</Waterfall>
</div>
<!-- 加载更多提示 -->
<div v-if="imageList.length > 0" class="mt-4 flex justify-center py-4">
<Spin v-if="loading" />
<div
v-else-if="!hasMore"
class="text-sm text-gray-500 dark:text-gray-400"
>
没有更多图片了
</div>
</div>
</Spin>
</Card>
@@ -0,0 +1,342 @@
<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { ImageDTO, ImageVO } from '#/api/media/image/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref, watch } from 'vue';
import { Button, Image, message, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getImagePageApi } from '#/api/media/image';
defineOptions({ name: 'ImageListView' });
const props = defineProps<{
categoryOptions: Array<{ label: string; value: string }>;
searchForm: {
category?: string;
filename: string;
};
}>();
const emit = defineEmits<{
(e: 'edit', image: ImageVO.Info): void;
(e: 'delete', id: number): void;
(e: 'download', image: ImageVO.Info): void;
(e: 'update:searchForm', value: typeof props.searchForm): void;
}>();
// 响应式数据
const loading = ref(false);
// 本地搜索表单副本(用于 v-model)
const localSearchForm = ref({
filename: props.searchForm.filename,
category: props.searchForm.category,
});
// 监听 props 变化,同步到本地
watch(
() => props.searchForm,
(newForm) => {
if (
localSearchForm.value.filename !== newForm.filename ||
localSearchForm.value.category !== newForm.category
) {
localSearchForm.value.filename = newForm.filename;
localSearchForm.value.category = newForm.category;
refreshTable();
}
},
{ deep: true },
);
// 监听本地表单变化,同步到父组件
watch(
localSearchForm,
(newForm) => {
if (
props.searchForm.filename !== newForm.filename ||
props.searchForm.category !== newForm.category
) {
emit('update:searchForm', { ...newForm });
}
},
{ deep: true },
);
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
minWidth: 'auto',
title: '序号',
},
{
title: '预览',
width: '60',
slots: { default: 'preview' },
},
{
field: 'filename',
title: '文件名',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
title: '分类',
minWidth: 'auto',
slots: { default: 'category' },
},
{
title: '标签',
minWidth: 'auto',
slots: { default: 'tags' },
},
{
field: 'remark',
title: '说明',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
field: 'uploadTime',
title: '上传时间',
minWidth: 'auto',
},
{
title: '操作',
minWidth: 'auto',
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
// 配置远程加载
proxyConfig: {
ajax: {
query: async ({ page }) => {
try {
loading.value = true;
const params: PageQueryDTO<ImageDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
filename: localSearchForm.value.filename || undefined,
category: localSearchForm.value.category || undefined,
},
};
const data = await getImagePageApi(params);
return {
items: data.records,
total: data.total,
};
} catch (error) {
console.error('获取图片列表失败:', error);
message.error('获取图片列表失败');
return {
items: [],
total: 0,
};
} finally {
loading.value = false;
}
},
},
},
};
// 搜索表单配置
const formOptions = computed(() => ({
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入文件名',
},
fieldName: 'filename',
label: '文件名',
},
{
component: 'Select',
componentProps: {
placeholder: '请选择图片分类',
options: props.categoryOptions,
allowClear: true,
},
fieldName: 'category',
label: '图片分类',
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
// 刷新表格数据
function refreshTable() {
if (gridApi) {
gridApi.reload();
}
}
// 创建 VbenVxeGrid 实例
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '图片管理',
});
// 事件处理
const handleEdit = (image: ImageVO.Info) => {
emit('edit', image);
};
const handleDelete = (id: number) => {
emit('delete', id);
};
const handleDownload = (image: ImageVO.Info) => {
emit('download', image);
};
// 预览功能在列表视图中直接通过 Image 组件的 preview 属性实现
// const handlePreview = (image: ImageVO.Info) => {
// emit('preview', image);
// };
// 获取分类标签颜色
const getCategoryColor = (category: string | undefined) => {
switch (category) {
case 'avatar': {
return 'green';
}
case 'image': {
return 'blue';
}
case 'logo': {
return 'purple';
}
default: {
return 'default';
}
}
};
// 获取分类显示文本
const getCategoryText = (category: string | undefined) => {
switch (category) {
case 'avatar': {
return '头像';
}
case 'image': {
return '普通图片';
}
case 'logo': {
return 'Logo';
}
default: {
return '未分类';
}
}
};
// 获取标签列表
const getTagList = (tags: string | undefined) => {
if (!tags) return [];
return tags
.split(',')
.map((tag) => tag.trim())
.filter(Boolean);
};
// 暴露刷新方法
defineExpose({
refreshTable,
});
</script>
<template>
<Grid :loading="loading">
<!-- 预览列 -->
<template #preview="{ row }: { row: any }">
<Image
:src="row.url"
:alt="row.filename"
width="40"
height="40"
style="object-fit: cover; border-radius: 4px"
:preview="true"
/>
</template>
<!-- 分类列 -->
<template #category="{ row }: { row: any }">
<Tag :color="getCategoryColor(row.category)">
{{ getCategoryText(row.category) }}
</Tag>
</template>
<!-- 标签列 -->
<template #tags="{ row }: { row: any }">
<div v-if="row.tags" class="flex flex-wrap gap-1">
<Tag
v-for="tag in getTagList(row.tags)"
:key="tag"
size="small"
color="blue"
>
{{ tag }}
</Tag>
</div>
<span v-else class="text-gray-400">无标签</span>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleDownload(row)"> 下载 </Button>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" danger @click="handleDelete(row.id)">
删除
</Button>
</Space>
</template>
</Grid>
</template>