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
+2 -1
View File
@@ -46,7 +46,8 @@
"papaparse": "^5.4.1", "papaparse": "^5.4.1",
"pinia": "catalog:", "pinia": "catalog:",
"vue": "catalog:", "vue": "catalog:",
"vue-router": "catalog:" "vue-router": "catalog:",
"vue-waterfall-plugin-next": "^3.0.0"
}, },
"devDependencies": { "devDependencies": {
"@types/papaparse": "^5.3.14" "@types/papaparse": "^5.3.14"
@@ -1,34 +1,22 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table'; import type { ImageVO } from '#/api/media/image/types';
import type { ImageDTO, ImageVO } from '#/api/media/image/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue'; import { ref } from 'vue';
import { Page } from '@vben/common-ui'; import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons'; import { createIconifyIcon } from '@vben/icons';
import { import { Button, Divider, Flex, message, Space, Upload } from 'ant-design-vue';
Button,
Divider,
Flex,
Image,
message,
Space,
Tag,
Upload,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { import {
batchUploadImagesApi, batchUploadImagesApi,
deleteImageApi, deleteImageApi,
getImagePageApi,
uploadImageApi, uploadImageApi,
} from '#/api/media/image'; } from '#/api/media/image';
import ImageEditModal from './components/ImageEditModal.vue'; import ImageEditModal from './components/ImageEditModal.vue';
import ImageGridView from './views/ImageGridView/index.vue'; import ImageGridView from './views/ImageGridView/index.vue';
import ImageListView from './views/ImageListView/index.vue';
defineOptions({ name: 'ImageRepository' }); defineOptions({ name: 'ImageRepository' });
// 创建图标组件 // 创建图标组件
@@ -37,7 +25,6 @@ const GridIcon = createIconifyIcon('lucide:grid-3x3');
const ListIcon = createIconifyIcon('lucide:list'); const ListIcon = createIconifyIcon('lucide:list');
// 响应式数据 // 响应式数据
const loading = ref(false);
const editModalVisible = ref(false); const editModalVisible = ref(false);
const currentImageData = ref<ImageVO.Info | null>(null); const currentImageData = ref<ImageVO.Info | null>(null);
const uploadLoading = ref(false); const uploadLoading = ref(false);
@@ -56,163 +43,19 @@ const imageCategoryOptions = [
{ label: 'Logo', value: 'logo' }, { label: 'Logo', value: 'logo' },
]; ];
// VbenVxeGrid 表格配置 // 列表视图和网格视图引用
const gridOptions: VxeGridProps<any> = { const imageListViewRef = ref<null | { refreshTable: () => void }>(null);
columns: [ const imageGridViewRef = ref<null | { refreshTable: () => void }>(null);
{
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,
}));
// 刷新表格数据 // 刷新表格数据
function refreshTable() { function refreshTable() {
if (gridApi) { if (viewMode.value === 'list' && imageListViewRef.value) {
gridApi.reload(); 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) => { const handleUpload = async (file: File) => {
uploadLoading.value = true; uploadLoading.value = true;
@@ -271,6 +114,11 @@ const handleDelete = async (id: number) => {
} }
}; };
// 处理列表视图删除
const handleListViewDelete = (id: number) => {
handleDelete(id);
};
// 处理编辑成功 // 处理编辑成功
const handleEditSuccess = () => { const handleEditSuccess = () => {
refreshTable(); 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> </script>
<template> <template>
@@ -391,56 +194,20 @@ const getTagList = (tags: string | undefined) => {
</template> </template>
<!-- 列表视图 --> <!-- 列表视图 -->
<Grid v-if="viewMode === 'list'" :loading="loading"> <ImageListView
<!-- 预览列 --> v-if="viewMode === 'list'"
<template #preview="{ row }: { row: any }"> ref="imageListViewRef"
<Image v-model:search-form="searchForm"
:src="row.url" :category-options="imageCategoryOptions"
:alt="row.filename" @edit="handleEdit"
width="60" @delete="handleListViewDelete"
height="60" @download="handleDownload"
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>
<!-- 网格视图 --> <!-- 网格视图 -->
<ImageGridView <ImageGridView
v-else v-else
ref="imageGridViewRef"
v-model:search-form="searchForm" v-model:search-form="searchForm"
:category-options="imageCategoryOptions" :category-options="imageCategoryOptions"
:upload-loading="uploadLoading" :upload-loading="uploadLoading"
@@ -449,14 +216,15 @@ const getTagList = (tags: string | undefined) => {
@download="handleDownload" @download="handleDownload"
@preview="handlePreview" @preview="handlePreview"
/> />
<!-- 编辑弹窗 -->
<ImageEditModal
v-model:open="editModalVisible"
:image-data="currentImageData"
@success="handleEditSuccess"
@cancel="editModalVisible = false"
/>
</Page> </Page>
<!-- 编辑弹窗 -->
<ImageEditModal
v-model:open="editModalVisible"
:image-data="currentImageData"
@success="handleEditSuccess"
@cancel="editModalVisible = false"
/>
</template> </template>
<style scoped> <style scoped>
@@ -80,15 +80,19 @@ const getTagList = (tags: string | undefined) => {
</script> </script>
<template> <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 <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 <Image
:src="image.url" :src="image.url"
:alt="image.filename" :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" :preview="true"
/> />
@@ -172,20 +176,3 @@ const getTagList = (tags: string | undefined) => {
</div> </div>
</Card> </Card>
</template> </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 { ImageDTO, ImageVO } from '#/api/media/image/types';
import type { PageQueryDTO } from '#/types/common'; 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 { import {
Button, Button,
Card, Card,
Col, Empty,
Flex,
Form, Form,
Input, Input,
message, message,
Pagination,
Row,
Select, Select,
Space, Space,
Spin, Spin,
@@ -46,7 +47,14 @@ const loading = ref(false);
const imageList = ref<ImageVO.Info[]>([]); const imageList = ref<ImageVO.Info[]>([]);
const total = ref(0); const total = ref(0);
const current = ref(1); 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) // 本地搜索表单副本(用于 v-model)
const localSearchForm = ref({ const localSearchForm = ref({
@@ -64,8 +72,11 @@ watch(
) { ) {
localSearchForm.value.filename = newForm.filename; localSearchForm.value.filename = newForm.filename;
localSearchForm.value.category = newForm.category; localSearchForm.value.category = newForm.category;
// 重置分页和列表
current.value = 1; current.value = 1;
loadImageList(); imageList.value = [];
hasMore.value = true;
loadImageList(true);
} }
}, },
{ deep: 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; loading.value = true;
try { try {
const params: PageQueryDTO<ImageDTO.Filters> = { const params: PageQueryDTO<ImageDTO.Filters> = {
@@ -99,8 +112,22 @@ const loadImageList = async () => {
}; };
const response = await getImagePageApi(params); 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; total.value = response.total;
// 判断是否还有更多数据
if (imageList.value.length >= response.total) {
hasMore.value = false;
} else {
current.value++;
hasMore.value = true;
}
} catch { } catch {
message.error('加载图片列表失败'); message.error('加载图片列表失败');
} finally { } finally {
@@ -111,7 +138,9 @@ const loadImageList = async () => {
// 搜索 // 搜索
const handleSearch = () => { const handleSearch = () => {
current.value = 1; current.value = 1;
loadImageList(); imageList.value = [];
hasMore.value = true;
loadImageList(true);
}; };
// 重置 // 重置
@@ -121,11 +150,16 @@ const handleReset = () => {
handleSearch(); handleSearch();
}; };
// 分页变化 // 滚动监听
const handlePageChange = (page: number, size: number) => { const handleScroll = () => {
current.value = page; const container = scrollContainerRef.value;
pageSize.value = size; if (!container || loading.value || !hasMore.value) return;
loadImageList();
const { scrollTop, scrollHeight, clientHeight } = container;
// 当滚动到距离底部 200px 时加载更多
if (scrollTop + clientHeight >= scrollHeight - 200) {
loadImageList();
}
}; };
// 事件处理 // 事件处理
@@ -145,16 +179,40 @@ const handlePreview = (image: ImageVO.Info) => {
emit('preview', image); 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> </script>
<template> <template>
<div class="flex-col"> <div class="flex h-full flex-col">
<!-- 搜索区域 --> <!-- 搜索区域 -->
<Card class="mb-4" :body-style="{ padding: '16px' }"> <Card class="mb-4" :body-style="{ padding: '16px' }">
<Form :model="localSearchForm" layout="inline" class="w-full"> <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"> <Form.Item label="文件名" class="mb-0">
<Input <Input
v-model:value="localSearchForm.filename" v-model:value="localSearchForm.filename"
@@ -189,57 +247,69 @@ loadImageList();
<div class="ml-auto text-sm text-gray-500 dark:text-gray-400"> <div class="ml-auto text-sm text-gray-500 dark:text-gray-400">
共 {{ total }} 张图片 共 {{ total }} 张图片
</div> </div>
</div> </Flex>
</Form> </Form>
</Card> </Card>
<!-- 网格内容 --> <!-- 网格内容 -->
<Card class="flex-1" :body-style="{ padding: '16px' }"> <Card
<Spin :spinning="loading"> class="flex flex-1 flex-col overflow-y-auto"
<Row :gutter="[16, 16]"> :body-style="{
<Col padding: '16px',
v-for="image in imageList" display: 'flex',
:key="image.id" flexDirection: 'column',
:xs="12" height: '100%',
:sm="8" }"
:md="6" >
:lg="4" <Spin :spinning="loading && imageList.length === 0">
:xl="3"
>
<ImageCard
:image="image"
@download="handleDownload"
@edit="handleEdit"
@delete="handleDelete"
@preview="handlePreview"
/>
</Col>
</Row>
<!-- 空状态 --> <!-- 空状态 -->
<div <div
v-if="!loading && imageList.length === 0" 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> <Empty />
<div class="mb-2 text-lg text-gray-400">暂无图片数据</div>
<div class="text-sm text-gray-400">请上传图片或调整搜索条件</div>
</div> </div>
<!-- 分页 --> <!-- 瀑布流 -->
<div v-if="total > 0" class="mt-6 flex justify-center"> <div ref="scrollContainerRef" class="flex-1 overflow-auto">
<Pagination <Waterfall
v-model:current="current" v-if="imageList.length > 0"
v-model:page-size="pageSize" :list="displayList"
:total="total" row-key="id"
:page-size-options="['12', '24', '48', '96']" :width="280"
show-size-changer :breakpoints="{
show-quick-jumper 1600: { rowPerView: 5 },
:show-total=" 1400: { rowPerView: 4 },
(total, range) => `第 ${range[0]}-${range[1]} 条,共 ${total} 条` 1200: { rowPerView: 4 },
" 992: { rowPerView: 3 },
@change="handlePageChange" 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> </div>
</Spin> </Spin>
</Card> </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>
@@ -3,15 +3,7 @@ import type { ProductVO } from '#/api/shop/product/types';
import { createIconifyIcon } from '@vben/icons'; import { createIconifyIcon } from '@vben/icons';
import { import { Button, Card, Image, Popconfirm, Space, Tag } from 'ant-design-vue';
Button,
Card,
Image,
Popconfirm,
Space,
Tag,
Tooltip,
} from 'ant-design-vue';
defineProps<Props>(); defineProps<Props>();
const emit = defineEmits<Emits>(); const emit = defineEmits<Emits>();
@@ -19,7 +11,6 @@ const emit = defineEmits<Emits>();
const EditIcon = createIconifyIcon('lucide:edit'); const EditIcon = createIconifyIcon('lucide:edit');
const TrashIcon = createIconifyIcon('lucide:trash-2'); const TrashIcon = createIconifyIcon('lucide:trash-2');
const SettingsIcon = createIconifyIcon('lucide:settings'); const SettingsIcon = createIconifyIcon('lucide:settings');
const EyeIcon = createIconifyIcon('lucide:eye');
interface Props { interface Props {
product: ProductVO.Info; product: ProductVO.Info;
@@ -29,7 +20,6 @@ interface Emits {
(e: 'edit', product: ProductVO.Info): void; (e: 'edit', product: ProductVO.Info): void;
(e: 'delete', product: ProductVO.Info): void; (e: 'delete', product: ProductVO.Info): void;
(e: 'manageSpecs', product: ProductVO.Info): void; (e: 'manageSpecs', product: ProductVO.Info): void;
(e: 'viewDetails', product: ProductVO.Info): void;
} }
const handleEdit = (product: ProductVO.Info) => { const handleEdit = (product: ProductVO.Info) => {
@@ -43,51 +33,32 @@ const handleDelete = (product: ProductVO.Info) => {
const handleManageSpecs = (product: ProductVO.Info) => { const handleManageSpecs = (product: ProductVO.Info) => {
emit('manageSpecs', product); emit('manageSpecs', product);
}; };
const handleViewDetails = (product: ProductVO.Info) => {
emit('viewDetails', product);
};
const handleImageError = (event: Event | string) => {
if (typeof event === 'string') {
// 如果是字符串,说明是错误信息,直接隐藏图片
const img = document.querySelector(
`img[src="${event}"]`,
) as HTMLImageElement;
if (img) {
img.style.display = 'none';
}
} else {
// 如果是Event对象,按原来的方式处理
const img = event.target as HTMLImageElement;
if (img) {
img.style.display = 'none';
}
}
};
</script> </script>
<template> <template>
<Card hoverable :body-style="{ padding: '12px' }" class="product-card"> <Card
<div class="relative"> hoverable
<!-- 商品图片 --> :body-style="{ padding: 0 }"
<div class="aspect-square overflow-hidden rounded-lg bg-gray-100"> class="group h-full 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"
<Image >
v-if="product.mainImage" <!-- 图片区域 -->
:src="product.mainImage" <div
:alt="product.name" class="relative aspect-square cursor-pointer overflow-hidden rounded-t-lg bg-gray-100 dark:bg-neutral-800"
class="h-full w-full object-cover" >
:preview="true" <Image
@error="handleImageError" v-if="product.mainImage"
/> :src="product.mainImage"
<div :alt="product.name"
v-else class="h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
class="flex h-full w-full items-center justify-center text-gray-400" :preview="true"
> />
<div class="text-center"> <div
<div class="mb-2 text-4xl">📦</div> v-else
<div class="text-sm">暂无图片</div> class="flex h-full w-full items-center justify-center text-gray-400 dark:text-gray-500"
</div> >
<div class="text-center">
<div class="mb-2 text-4xl">📦</div>
<div class="text-sm">暂无图片</div>
</div> </div>
</div> </div>
@@ -96,77 +67,101 @@ const handleImageError = (event: Event | string) => {
v-if="product.specs && product.specs.length > 0" v-if="product.specs && product.specs.length > 0"
class="absolute left-2 top-2" class="absolute left-2 top-2"
> >
<Tag color="blue"> {{ product.specs.length }} 个规格 </Tag> <Tag color="blue" size="small"> {{ product.specs.length }} 个规格 </Tag>
</div>
<!-- 如果有多个规格,显示更多标识 -->
<div
v-if="product.specs && product.specs.length > 3"
class="absolute right-2 top-2"
>
<Tag color="orange" size="small"> +{{ product.specs.length - 3 }} </Tag>
</div> </div>
</div> </div>
<!-- 商品信息 --> <!-- 信息区域 -->
<div class="mt-3"> <div class="p-3">
<!-- 商品名称 -->
<div <div
class="mb-2 line-clamp-2 text-sm font-medium text-gray-900" class="mb-2 line-clamp-2 text-sm font-medium text-gray-900 dark:text-gray-100"
:title="product.name" :title="product.name"
> >
{{ product.name }} {{ product.name }}
</div> </div>
<!-- 规格信息 --> <!-- 规格信息预览 -->
<div v-if="product.specs && product.specs.length > 0" class="mb-2"> <div
<div class="mb-1 text-xs text-gray-500">规格信息:</div> v-if="product.specs && product.specs.length > 0"
<div class="space-y-1"> class="mb-3 space-y-1"
<div >
v-for="spec in product.specs.slice(0, 2)" <div
:key="spec.id" v-for="spec in product.specs.slice(0, 2)"
class="rounded bg-gray-50 px-2 py-1 text-xs" :key="spec.id"
> class="flex items-center justify-between rounded-md bg-gray-50 px-2 py-1 text-xs dark:bg-neutral-800"
<span class="font-medium">{{ spec.name }}</span> >
<span class="ml-1 text-red-500"> <span class="font-medium text-gray-700 dark:text-gray-300">{{
¥{{ spec.costPrice.toFixed(2) }} spec.name
</span> }}</span>
</div> <span class="ml-2 font-semibold text-red-500 dark:text-red-400">
<div v-if="product.specs.length > 2" class="text-xs text-gray-400"> ¥{{ spec.costPrice.toFixed(2) }}
还有 {{ product.specs.length - 2 }} 个规格... </span>
</div> </div>
<div
v-if="product.specs.length > 2"
class="text-xs text-gray-400 dark:text-gray-500"
>
还有 {{ product.specs.length - 2 }} 个规格...
</div> </div>
</div> </div>
<!-- 创建时间 --> <!-- 创建时间 -->
<div class="mb-3 text-xs text-gray-500"> <div class="mb-3 text-xs text-gray-500 dark:text-gray-400">
{{ product.createTime }} {{ product.createTime }}
</div> </div>
<!-- 操作按钮 --> <!-- 操作按钮 -->
<div class="flex items-center justify-between"> <div class="flex w-full items-center justify-between gap-1">
<Space size="small"> <Space size="small">
<Tooltip title="编辑"> <Button
<Button type="text" size="small" @click="handleEdit(product)"> type="text"
size="small"
@click="handleEdit(product)"
title="编辑"
class="min-w-0 flex-1"
>
<template #icon>
<EditIcon class="h-4 w-4" /> <EditIcon class="h-4 w-4" />
</Button> </template>
</Tooltip> <span class="hidden sm:inline">编辑</span>
<Tooltip title="管理规格"> </Button>
<Button <Button
type="text" type="text"
size="small" size="small"
@click="handleManageSpecs(product)" @click="handleManageSpecs(product)"
> title="管理规格"
class="min-w-0 flex-1"
>
<template #icon>
<SettingsIcon class="h-4 w-4" /> <SettingsIcon class="h-4 w-4" />
</Button> </template>
</Tooltip> <span class="hidden sm:inline">规格</span>
<Tooltip title="查看详情"> </Button>
<Button
type="text"
size="small"
@click="handleViewDetails(product)"
>
<EyeIcon class="h-4 w-4" />
</Button>
</Tooltip>
</Space> </Space>
<Popconfirm <Popconfirm
title="确定要删除这个商品吗?" title="确定要删除这个商品吗?"
@confirm="handleDelete(product)" @confirm="handleDelete(product)"
> >
<Button type="text" size="small" danger> <Button
<TrashIcon class="h-4 w-4" /> type="text"
size="small"
danger
title="删除"
class="flex-shrink-0"
>
<template #icon>
<TrashIcon class="h-4 w-4" />
</template>
<span class="hidden sm:inline">删除</span>
</Button> </Button>
</Popconfirm> </Popconfirm>
</div> </div>
@@ -175,16 +170,6 @@ const handleImageError = (event: Event | string) => {
</template> </template>
<style scoped> <style scoped>
.product-card {
transition: all 0.3s ease;
height: 100%;
}
.product-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.line-clamp-2 { .line-clamp-2 {
display: -webkit-box; display: -webkit-box;
-webkit-line-clamp: 2; -webkit-line-clamp: 2;
@@ -1,33 +1,19 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table'; import type { ProductVO } from '#/api/shop/product/types';
import type { ProductDTO, ProductVO } from '#/api/shop/product/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue'; import { ref } from 'vue';
import { Page } from '@vben/common-ui'; import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons'; import { createIconifyIcon } from '@vben/icons';
import { import { Button, Divider, Flex, Space } from 'ant-design-vue';
Button,
Col,
Form,
Input,
InputNumber,
message,
Pagination,
Row,
Space,
Tag,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table'; import { deleteProductApi } from '#/api/shop/product';
import { deleteProductApi, getProductPageApi } from '#/api/shop/product';
import ProductCard from './components/ProductCard.vue';
import ProductFormModal from './components/ProductFormModal.vue'; import ProductFormModal from './components/ProductFormModal.vue';
// @ts-ignore
import ProductSpecModal from './components/ProductSpecModal.vue'; import ProductSpecModal from './components/ProductSpecModal.vue';
import ProductGridView from './views/ProductGridView/index.vue';
import ProductListView from './views/ProductListView/index.vue';
defineOptions({ name: 'ProductManagement' }); defineOptions({ name: 'ProductManagement' });
// 创建图标组件 // 创建图标组件
@@ -36,14 +22,11 @@ const ListIcon = createIconifyIcon('lucide:list');
const PlusIcon = createIconifyIcon('lucide:plus'); const PlusIcon = createIconifyIcon('lucide:plus');
// 响应式数据 // 响应式数据
const loading = ref(false);
const productList = ref<ProductVO.Info[]>([]);
const total = ref(0);
const current = ref(1);
const pageSize = ref(10);
const viewMode = ref<'grid' | 'table'>('grid'); const viewMode = ref<'grid' | 'table'>('grid');
const productFormModalRef = ref(); const productFormModalRef = ref();
const productSpecModalRef = ref(); const productSpecModalRef = ref();
const productListViewRef = ref<null | { refreshTable: () => void }>(null);
const productGridViewRef = ref<null | { refreshTable: () => void }>(null);
// 搜索表单 // 搜索表单
const searchForm = ref({ const searchForm = ref({
@@ -54,202 +37,15 @@ const searchForm = ref({
maxCostPrice: undefined as number | undefined, maxCostPrice: undefined as number | undefined,
}); });
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
minWidth: 'auto',
title: '序号',
},
{
field: 'name',
title: '商品名称',
minWidth: 200,
showOverflow: 'tooltip' as const,
},
{
title: '主图',
minWidth: 100,
slots: { default: 'mainImage' },
},
{
title: '规格数量',
minWidth: 100,
slots: { default: 'specs' },
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
},
{
field: 'updateTime',
title: '更新时间',
minWidth: 180,
},
{
title: '操作',
minWidth: 200,
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<ProductDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
name: searchForm.value.name || undefined,
specCode: searchForm.value.specCode || undefined,
skuCode: searchForm.value.skuCode || undefined,
minCostPrice: searchForm.value.minCostPrice,
maxCostPrice: searchForm.value.maxCostPrice,
},
};
const data = await getProductPageApi(params);
productList.value = data.records;
total.value = data.total;
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: 'name',
label: '商品名称',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入商品编码',
},
fieldName: 'specCode',
label: '商品编码',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入商品SKU',
},
fieldName: 'skuCode',
label: '商品SKU',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '最小值',
min: 0,
precision: 2,
style: { width: '100%' },
},
fieldName: 'minCostPrice',
label: '成本价最小值',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '最大值',
min: 0,
precision: 2,
style: { width: '100%' },
},
fieldName: 'maxCostPrice',
label: '成本价最大值',
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
// 刷新表格数据 // 刷新表格数据
function refreshTable() { function refreshTable() {
if (gridApi) { if (viewMode.value === 'table' && productListViewRef.value) {
gridApi.reload(); productListViewRef.value.refreshTable();
} else if (viewMode.value === 'grid' && productGridViewRef.value) {
productGridViewRef.value.refreshTable();
} }
} }
// 处理重置
function handleReset() {
searchForm.value = {
name: '',
specCode: '',
skuCode: '',
minCostPrice: undefined,
maxCostPrice: undefined,
};
current.value = 1;
refreshTable();
}
// 处理分页变化
function handleTableChange(pagination: any) {
current.value = pagination.current;
pageSize.value = pagination.pageSize;
refreshTable();
}
// 处理添加商品 // 处理添加商品
function handleAdd() { function handleAdd() {
productFormModalRef.value?.open(false); productFormModalRef.value?.open(false);
@@ -264,23 +60,25 @@ function handleEdit(record: ProductVO.Info) {
async function handleDelete(record: ProductVO.Info) { async function handleDelete(record: ProductVO.Info) {
try { try {
await deleteProductApi(record.id); await deleteProductApi(record.id);
message.success('删除成功');
refreshTable(); refreshTable();
} catch (error) { } catch (error) {
console.error('删除商品失败:', error); console.error('删除商品失败:', error);
message.error('删除商品失败');
} }
} }
// 处理列表视图删除
const handleListViewDelete = (product: ProductVO.Info) => {
handleDelete(product);
};
// 处理管理规格 // 处理管理规格
function handleManageSpecs(record: ProductVO.Info) { function handleManageSpecs(record: ProductVO.Info) {
productSpecModalRef.value?.open(record); productSpecModalRef.value?.open(record);
} }
// 处理查看详情 // 切换视图模式
function handleViewDetails() { function toggleViewMode() {
// TODO: 实现查看详情功能 viewMode.value = viewMode.value === 'grid' ? 'table' : 'grid';
message.info('查看详情功能待实现');
} }
// 处理模态框成功 // 处理模态框成功
@@ -293,198 +91,60 @@ function handleSpecModalSuccess() {
// 规格管理成功后可能需要刷新商品列表 // 规格管理成功后可能需要刷新商品列表
refreshTable(); refreshTable();
} }
// 创建 VbenVxeGrid 实例
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '商品管理',
});
</script> </script>
<template> <template>
<Page title="商品管理" auto-content-height> <Page :auto-content-height="true" content-class="flex-col">
<template #description> <!-- 工具栏区域 -->
<div class="text-foreground/80 mt-2">
管理商品信息,支持商品和规格的一键创建,提供网格和列表两种视图模式
</div>
</template>
<template #extra> <template #extra>
<div class="flex items-center gap-2"> <Flex gap="small" align="center">
<Button
:type="viewMode === 'grid' ? 'primary' : 'default'"
@click="viewMode = 'grid'"
>
<GridIcon class="mr-2 h-4 w-4" />
网格视图
</Button>
<Button
:type="viewMode === 'table' ? 'primary' : 'default'"
@click="viewMode = 'table'"
>
<ListIcon class="mr-2 h-4 w-4" />
列表视图
</Button>
</div>
</template>
<!-- 列表视图 -->
<Grid v-if="viewMode === 'table'" :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space> <Space>
<Button type="primary" @click="handleAdd">
<PlusIcon />
添加商品
</Button>
</Space>
</template>
<!-- 主图列 -->
<template #mainImage="{ row }: { row: any }">
<div v-if="row.mainImage">
<img
:src="row.mainImage"
:alt="row.name"
style="
width: 40px;
height: 40px;
object-fit: cover;
border-radius: 4px;
"
/>
</div>
<span v-else style="color: #999">暂无图片</span>
</template>
<!-- 规格数量列 -->
<template #specs="{ row }: { row: any }">
<Tag :color="(row.specs?.length || 0) > 0 ? 'blue' : 'default'">
{{ row.specs?.length || 0 }} 个规格
</Tag>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" @click="handleManageSpecs(row)"> 规格 </Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
<!-- 网格视图 -->
<div v-if="viewMode === 'grid'">
<!-- 搜索表单 -->
<div class="mb-4 rounded-lg bg-white p-4 shadow-sm">
<Form :model="searchForm" layout="inline">
<Form.Item label="商品名称">
<Input
v-model:value="searchForm.name"
placeholder="请输入商品名称"
style="width: 200px"
@press-enter="refreshTable"
/>
</Form.Item>
<Form.Item label="商品编码">
<Input
v-model:value="searchForm.specCode"
placeholder="请输入商品编码"
style="width: 150px"
@press-enter="refreshTable"
/>
</Form.Item>
<Form.Item label="商品SKU">
<Input
v-model:value="searchForm.skuCode"
placeholder="请输入商品SKU"
style="width: 150px"
@press-enter="refreshTable"
/>
</Form.Item>
<Form.Item label="成本价范围">
<div class="flex items-center gap-2">
<InputNumber
v-model:value="searchForm.minCostPrice"
placeholder="最小值"
style="width: 100px"
:min="0"
:precision="2"
/>
<span class="text-gray-500">-</span>
<InputNumber
v-model:value="searchForm.maxCostPrice"
placeholder="最大值"
style="width: 100px"
:min="0"
:precision="2"
/>
</div>
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" @click="refreshTable">搜索</Button>
<Button @click="handleReset">重置</Button>
</Space>
</Form.Item>
</Form>
</div>
<!-- 工具栏 -->
<div class="mb-4 flex items-center justify-between">
<div class="flex items-center gap-4">
<Button type="primary" @click="handleAdd"> <Button type="primary" @click="handleAdd">
<PlusIcon class="mr-2 h-4 w-4" /> <PlusIcon class="mr-2 h-4 w-4" />
添加商品 添加商品
</Button> </Button>
<span class="text-gray-500">支持商品和规格的一键创建</span> </Space>
</div>
<div class="flex items-center gap-2">
<span class="text-gray-500">共 {{ total }} 个商品</span>
</div>
</div>
<!-- 网格内容 --> <Divider type="vertical" />
<div class="rounded-lg bg-white p-4 shadow-sm">
<Row :gutter="[16, 16]"> <Space>
<Col <Button
v-for="product in productList" :type="viewMode === 'grid' ? 'primary' : 'default'"
:key="product.id" @click="toggleViewMode"
:xs="12"
:sm="8"
:md="6"
:lg="4"
:xl="3"
> >
<ProductCard <GridIcon class="mr-2 h-4 w-4" />
:product="product" 网格视图
@edit="handleEdit" </Button>
@delete="handleDelete" <Button
@manage-specs="handleManageSpecs" :type="viewMode === 'table' ? 'primary' : 'default'"
@view-details="handleViewDetails" @click="toggleViewMode"
/> >
</Col> <ListIcon class="mr-2 h-4 w-4" />
</Row> 列表视图
</Button>
</Space>
</Flex>
</template>
<!-- 分页 --> <!-- 列表视图 -->
<div class="mt-4 flex justify-center"> <ProductListView
<Pagination v-if="viewMode === 'table'"
v-model:current="current" ref="productListViewRef"
v-model:page-size="pageSize" v-model:search-form="searchForm"
:total="total" @edit="handleEdit"
:show-size-changer="true" @delete="handleListViewDelete"
:show-quick-jumper="true" @manage-specs="handleManageSpecs"
:show-total=" />
(total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`
" <!-- 网格视图 -->
@change="handleTableChange" <ProductGridView
/> v-else
</div> ref="productGridViewRef"
</div> v-model:search-form="searchForm"
</div> @edit="handleEdit"
@delete="handleDelete"
@manage-specs="handleManageSpecs"
/>
<!-- 商品表单模态框 --> <!-- 商品表单模态框 -->
<ProductFormModal ref="productFormModalRef" @success="handleModalSuccess" /> <ProductFormModal ref="productFormModalRef" @success="handleModalSuccess" />
@@ -0,0 +1,354 @@
<script setup lang="ts">
import type { ProductDTO, ProductVO } from '#/api/shop/product/types';
import type { PageQueryDTO } from '#/types/common';
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,
Empty,
Flex,
Form,
Input,
InputNumber,
message,
Space,
Spin,
} from 'ant-design-vue';
import { getProductPageApi } from '#/api/shop/product';
import ProductCard from '../../components/ProductCard.vue';
defineOptions({ name: 'ProductGridView' });
const props = defineProps<{
searchForm: {
maxCostPrice?: number;
minCostPrice?: number;
name: string;
skuCode: string;
specCode: string;
};
}>();
const emit = defineEmits<{
(e: 'edit', product: ProductVO.Info): void;
(e: 'delete', product: ProductVO.Info): void;
(e: 'manageSpecs', product: ProductVO.Info): void;
(e: 'update:searchForm', value: typeof props.searchForm): void;
}>();
// 响应式数据
const loading = ref(false);
const productList = ref<ProductVO.Info[]>([]);
const total = ref(0);
const current = ref(1);
const pageSize = ref(24); // 无限滚动默认每页24个
const hasMore = ref(true); // 是否还有更多数据
const scrollContainerRef = ref<HTMLElement | null>(null);
// 显示列表(只包含商品数据,不包含占位项)
const displayList = computed(() => {
return productList.value;
});
// 本地搜索表单副本(用于 v-model)
const localSearchForm = ref({
name: props.searchForm.name,
specCode: props.searchForm.specCode,
skuCode: props.searchForm.skuCode,
minCostPrice: props.searchForm.minCostPrice,
maxCostPrice: props.searchForm.maxCostPrice,
});
// 监听 props 变化,同步到本地
watch(
() => props.searchForm,
(newForm) => {
if (
localSearchForm.value.name !== newForm.name ||
localSearchForm.value.specCode !== newForm.specCode ||
localSearchForm.value.skuCode !== newForm.skuCode ||
localSearchForm.value.minCostPrice !== newForm.minCostPrice ||
localSearchForm.value.maxCostPrice !== newForm.maxCostPrice
) {
localSearchForm.value.name = newForm.name;
localSearchForm.value.specCode = newForm.specCode;
localSearchForm.value.skuCode = newForm.skuCode;
localSearchForm.value.minCostPrice = newForm.minCostPrice;
localSearchForm.value.maxCostPrice = newForm.maxCostPrice;
// 重置分页和列表
current.value = 1;
productList.value = [];
hasMore.value = true;
loadProductList(true);
}
},
{ deep: true },
);
// 监听本地表单变化,同步到父组件
watch(
localSearchForm,
(newForm) => {
if (
props.searchForm.name !== newForm.name ||
props.searchForm.specCode !== newForm.specCode ||
props.searchForm.skuCode !== newForm.skuCode ||
props.searchForm.minCostPrice !== newForm.minCostPrice ||
props.searchForm.maxCostPrice !== newForm.maxCostPrice
) {
emit('update:searchForm', { ...newForm });
}
},
{ deep: true },
);
// 加载商品列表
const loadProductList = async (reset = false) => {
if (loading.value || (!hasMore.value && !reset)) return;
loading.value = true;
try {
const params: PageQueryDTO<ProductDTO.Filters> = {
page: current.value,
pageSize: pageSize.value,
filters: {
name: localSearchForm.value.name || undefined,
specCode: localSearchForm.value.specCode || undefined,
skuCode: localSearchForm.value.skuCode || undefined,
minCostPrice: localSearchForm.value.minCostPrice,
maxCostPrice: localSearchForm.value.maxCostPrice,
},
};
const response = await getProductPageApi(params);
if (reset) {
productList.value = response.records;
} else {
productList.value.push(...response.records);
}
total.value = response.total;
// 判断是否还有更多数据
if (productList.value.length >= response.total) {
hasMore.value = false;
} else {
current.value++;
hasMore.value = true;
}
} catch {
message.error('加载商品列表失败');
} finally {
loading.value = false;
}
};
// 搜索
const handleSearch = () => {
current.value = 1;
productList.value = [];
hasMore.value = true;
loadProductList(true);
};
// 重置
const handleReset = () => {
localSearchForm.value = {
name: '',
specCode: '',
skuCode: '',
minCostPrice: undefined,
maxCostPrice: undefined,
};
handleSearch();
};
// 滚动监听
const handleScroll = () => {
const container = scrollContainerRef.value;
if (!container || loading.value || !hasMore.value) return;
const { scrollTop, scrollHeight, clientHeight } = container;
// 当滚动到距离底部 200px 时加载更多
if (scrollTop + clientHeight >= scrollHeight - 200) {
loadProductList();
}
};
// 事件处理
const handleEdit = (product: ProductVO.Info) => {
emit('edit', product);
};
const handleDelete = (product: ProductVO.Info) => {
emit('delete', product);
};
const handleManageSpecs = (product: ProductVO.Info) => {
emit('manageSpecs', product);
};
// 刷新列表
function refreshTable() {
handleSearch();
}
// 暴露方法
defineExpose({
refreshTable,
});
// 滚动监听
onMounted(() => {
loadProductList(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 h-full flex-col">
<!-- 搜索区域 -->
<Card class="mb-4" :body-style="{ padding: '16px' }">
<Form :model="localSearchForm" layout="inline" class="w-full">
<Flex class="w-full" justify="end" align="center" gap="4">
<Form.Item label="商品名称" class="mb-0">
<Input
v-model:value="localSearchForm.name"
placeholder="请输入商品名称"
style="width: 200px"
allow-clear
@press-enter="handleSearch"
/>
</Form.Item>
<Form.Item label="商品编码" class="mb-0">
<Input
v-model:value="localSearchForm.specCode"
placeholder="请输入商品编码"
style="width: 150px"
allow-clear
@press-enter="handleSearch"
/>
</Form.Item>
<Form.Item label="商品SKU" class="mb-0">
<Input
v-model:value="localSearchForm.skuCode"
placeholder="请输入商品SKU"
style="width: 150px"
allow-clear
@press-enter="handleSearch"
/>
</Form.Item>
<Form.Item label="成本价范围" class="mb-0">
<div class="flex items-center gap-2">
<InputNumber
v-model:value="localSearchForm.minCostPrice"
placeholder="最小值"
style="width: 100px"
:min="0"
:precision="2"
/>
<span class="text-gray-500">-</span>
<InputNumber
v-model:value="localSearchForm.maxCostPrice"
placeholder="最大值"
style="width: 100px"
:min="0"
:precision="2"
/>
</div>
</Form.Item>
<Form.Item class="mb-0">
<Space>
<Button type="primary" @click="handleSearch">搜索</Button>
<Button @click="handleReset">重置</Button>
</Space>
</Form.Item>
<div class="ml-auto text-sm text-gray-500 dark:text-gray-400">
共 {{ total }} 个商品
</div>
</Flex>
</Form>
</Card>
<!-- 网格内容 -->
<Card
class="flex flex-1 flex-col overflow-y-auto"
:body-style="{
padding: '16px',
display: 'flex',
flexDirection: 'column',
height: '100%',
}"
>
<Spin :spinning="loading && productList.length === 0">
<!-- 空状态 -->
<div
v-if="!loading && productList.length === 0"
class="flex h-full items-center justify-center py-8"
>
<Empty />
</div>
<!-- 瀑布流 -->
<Waterfall
v-else-if="productList.length > 0"
:list="displayList"
row-key="id"
:width="300"
:breakpoints="{
1600: { rowPerView: 4 },
1400: { rowPerView: 3 },
1200: { rowPerView: 3 },
992: { rowPerView: 2 },
768: { rowPerView: 2 },
500: { rowPerView: 1 },
}"
:gutter="16"
>
<template #default="{ item }">
<div class="w-full">
<ProductCard
:product="item"
@edit="handleEdit"
@delete="handleDelete"
@manage-specs="handleManageSpecs"
/>
</div>
</template>
</Waterfall>
<!-- 加载更多提示 -->
<div
v-if="productList.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>
</div>
</template>
@@ -0,0 +1,314 @@
<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { ProductDTO, ProductVO } from '#/api/shop/product/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 { getProductPageApi } from '#/api/shop/product';
defineOptions({ name: 'ProductListView' });
const props = defineProps<{
searchForm: {
maxCostPrice?: number;
minCostPrice?: number;
name: string;
skuCode: string;
specCode: string;
};
}>();
const emit = defineEmits<{
(e: 'edit', product: ProductVO.Info): void;
(e: 'delete', product: ProductVO.Info): void;
(e: 'manageSpecs', product: ProductVO.Info): void;
(e: 'update:searchForm', value: typeof props.searchForm): void;
}>();
// 响应式数据
const loading = ref(false);
// 本地搜索表单副本(用于 v-model)
const localSearchForm = ref({
name: props.searchForm.name,
specCode: props.searchForm.specCode,
skuCode: props.searchForm.skuCode,
minCostPrice: props.searchForm.minCostPrice,
maxCostPrice: props.searchForm.maxCostPrice,
});
// 监听 props 变化,同步到本地
watch(
() => props.searchForm,
(newForm) => {
if (
localSearchForm.value.name !== newForm.name ||
localSearchForm.value.specCode !== newForm.specCode ||
localSearchForm.value.skuCode !== newForm.skuCode ||
localSearchForm.value.minCostPrice !== newForm.minCostPrice ||
localSearchForm.value.maxCostPrice !== newForm.maxCostPrice
) {
localSearchForm.value.name = newForm.name;
localSearchForm.value.specCode = newForm.specCode;
localSearchForm.value.skuCode = newForm.skuCode;
localSearchForm.value.minCostPrice = newForm.minCostPrice;
localSearchForm.value.maxCostPrice = newForm.maxCostPrice;
refreshTable();
}
},
{ deep: true },
);
// 监听本地表单变化,同步到父组件
watch(
localSearchForm,
(newForm) => {
if (
props.searchForm.name !== newForm.name ||
props.searchForm.specCode !== newForm.specCode ||
props.searchForm.skuCode !== newForm.skuCode ||
props.searchForm.minCostPrice !== newForm.minCostPrice ||
props.searchForm.maxCostPrice !== newForm.maxCostPrice
) {
emit('update:searchForm', { ...newForm });
}
},
{ deep: true },
);
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
minWidth: 'auto',
title: '序号',
},
{
title: '主图',
width: 60,
slots: { default: 'mainImage' },
},
{
field: 'name',
title: '商品名称',
minWidth: 200,
showOverflow: 'tooltip' as const,
},
{
title: '规格数量',
minWidth: 100,
slots: { default: 'specs' },
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
},
{
field: 'updateTime',
title: '更新时间',
minWidth: 180,
},
{
title: '操作',
minWidth: 200,
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<ProductDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
name: localSearchForm.value.name || undefined,
specCode: localSearchForm.value.specCode || undefined,
skuCode: localSearchForm.value.skuCode || undefined,
minCostPrice: localSearchForm.value.minCostPrice,
maxCostPrice: localSearchForm.value.maxCostPrice,
},
};
const data = await getProductPageApi(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: 'name',
label: '商品名称',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入商品编码',
},
fieldName: 'specCode',
label: '商品编码',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入商品SKU',
},
fieldName: 'skuCode',
label: '商品SKU',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '最小值',
min: 0,
precision: 2,
style: { width: '100%' },
},
fieldName: 'minCostPrice',
label: '成本价最小值',
},
{
component: 'InputNumber',
componentProps: {
placeholder: '最大值',
min: 0,
precision: 2,
style: { width: '100%' },
},
fieldName: 'maxCostPrice',
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 = (product: ProductVO.Info) => {
emit('edit', product);
};
const handleDelete = (product: ProductVO.Info) => {
emit('delete', product);
};
const handleManageSpecs = (product: ProductVO.Info) => {
emit('manageSpecs', product);
};
// 暴露刷新方法
defineExpose({
refreshTable,
});
</script>
<template>
<Grid :loading="loading">
<!-- 主图列 -->
<template #mainImage="{ row }: { row: any }">
<Image
:src="row.mainImage"
:alt="row.name"
width="60"
height="60"
style="object-fit: cover; border-radius: 4px"
:preview="true"
/>
</template>
<!-- 规格数量列 -->
<template #specs="{ row }: { row: any }">
<Tag :color="(row.specs?.length || 0) > 0 ? 'blue' : 'default'">
{{ row.specs?.length || 0 }} 个规格
</Tag>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Button size="small" @click="handleManageSpecs(row)"> 规格 </Button>
<Button size="small" danger @click="handleDelete(row)"> 删除 </Button>
</Space>
</template>
</Grid>
</template>
+174 -1231
View File
File diff suppressed because it is too large Load Diff