feat(item): implement item editing functionality

This commit introduces the capability to edit existing items. The `ItemEditModal` has been refactored to support both creation and editing modes.

- The modal UI (title, buttons) and submission logic now adapt based on whether an item is being added or edited.
- A new `editItem` function is added to the `useItemsStore` to handle the update logic.
- Form validation for the item name is enhanced to correctly check for uniqueness during edits.
- The table's row action menu now opens the modal in edit mode, pre-populating the form.
- The `latestId` generation logic is improved for robustness.
- Additionally, this commit adds row selection checkboxes to the items table.
This commit is contained in:
xiaomai
2025-10-14 13:40:49 +08:00
parent 675704e4da
commit 1d2ce32ab9
3 changed files with 145 additions and 34 deletions

View File

@@ -1,11 +1,19 @@
<template>
<UModal v-model:open="open" title="新增物品" description="新增一件新的物品">
<UButton label="新增" icon="lucide:plus" />
<UModal
v-model:open="open"
:title="isEditMode ? '编辑物品' : '新增物品'"
:description="isEditMode ? '修改现有物品信息' : '新增一件新的物品'"
>
<UButton
label="新增"
icon="lucide:plus"
@click="openModal()"
/>
<template #body>
<UForm
ref="itemForm"
:schema="itemSchema"
:schema="formSchema"
:state="itemState"
@submit="onSubmit"
class="space-y-4"
@@ -59,7 +67,7 @@
@click="open = false"
/>
<UButton
label="创建"
:label="isEditMode ? '保存修改' : '创建'"
color="primary"
variant="solid"
@click="itemForm.submit()"
@@ -75,20 +83,34 @@ import * as z from "zod";
const itemForm = ref();
const open = ref<boolean>(false);
const toast = useToast();
const { stats, isNameAvailable, addItem } = useItemsStore();
const isEditMode = ref<boolean>(false);
const currentId = ref<number | null>(null);
const itemSchema = z.object({
name: z
.string()
.min(1, "名称不能为空")
.refine(isNameAvailable, "该名称已被占用,请更换一个"),
const toast = useToast();
const { stats, isNameAvailable, addItem, editItem, items } = useItemsStore();
// 🧩 基础校验(动态 schema
const baseSchema = z.object({
name: z.string().min(1, "名称不能为空"),
imageUrl: z.string().nullable().optional(),
description: z.string().nullable().optional(),
tags: z.string().nullable().optional(),
});
type ItemSchema = z.output<typeof itemSchema>;
// ⚙️ 根据模式动态生成 Schema编辑模式允许当前名称
const formSchema = computed(() =>
baseSchema.refine(
(data) =>
isEditMode.value
? !items.value.some(
(i) => i.name === data.name && i.id !== currentId.value
)
: isNameAvailable(data.name),
"该名称已被占用,请更换一个"
)
);
type ItemSchema = z.output<typeof baseSchema>;
const itemState = reactive<ItemSchema>({
name: "",
@@ -97,27 +119,74 @@ const itemState = reactive<ItemSchema>({
tags: null,
});
/** 🔧 打开 Modal新增 / 编辑) */
const openModal = (item?: Item) => {
if (item) {
// 编辑模式
isEditMode.value = true;
currentId.value = item.id;
itemState.name = item.name;
itemState.imageUrl = item.imageUrl ?? null;
itemState.description = item.description ?? null;
itemState.tags = item.tags?.join(", ") ?? null;
} else {
// 新增模式
isEditMode.value = false;
currentId.value = null;
itemState.name = "";
itemState.imageUrl = null;
itemState.description = null;
itemState.tags = null;
}
open.value = true;
};
const onSubmit = async (event: FormSubmitEvent<ItemSchema>) => {
const item: Item = {
id: stats.latestId.value,
name: event.data.name,
imageUrl: event.data.imageUrl,
description: event.data.description,
tags: event.data.tags?.split(",").map((tag) => tag.trim()),
createdAt: new Date(),
updatedAt: new Date(),
};
if (isEditMode.value && currentId.value !== null) {
// ✅ 编辑模式
const updatedItem: Item = {
id: currentId.value,
name: event.data.name,
imageUrl: event.data.imageUrl,
description: event.data.description,
tags: event.data.tags?.split(",").map((tag) => tag.trim()),
createdAt:
items.value.find((i) => i.id === currentId.value)?.createdAt ??
new Date(),
updatedAt: new Date(),
};
// TODO: Check is add or edit
addItem(item);
editItem(updatedItem);
toast.add({
title: "已保存修改",
description: `${event.data.name} 的信息已更新`,
color: "success",
});
} else {
// ✅ 新增模式
const newItem: Item = {
id: stats.latestId.value,
name: event.data.name,
imageUrl: event.data.imageUrl,
description: event.data.description,
tags: event.data.tags?.split(",").map((tag) => tag.trim()),
createdAt: new Date(),
updatedAt: new Date(),
};
addItem(newItem);
toast.add({
title: "成功",
description: `${event.data.name} 已添加到数据库中`,
color: "success",
});
}
toast.add({
title: "成功",
description: `${event.data.name} 已被添加到数据库中`,
color: "success",
});
open.value = false;
};
// expose method so parent can call modal.openModal(item)
defineExpose({ openModal });
</script>
<style></style>

View File

@@ -42,9 +42,11 @@ const _useItems = () => {
item.createdAt.getFullYear() === thisYear
).length;
}),
latestId: computed(
() => (items.value?.[items.value.length - 1]?.id ?? 0) + 1
),
latestId: computed(() => {
const arr = items.value ?? [];
if (arr.length === 0) return 1;
return Math.max(...arr.map((i) => i.id)) + 1;
}),
};
const isNameAvailable = (name: string) =>
@@ -54,11 +56,26 @@ const _useItems = () => {
items.value = [...(items.value ?? []), item]; // <-- 替换数组引用
};
const editItem = (item: Item) => {
const index = (items.value ?? []).findIndex((i) => i.id === item.id);
if (index === -1) return; // 未找到则直接返回
// 生成一个新的数组(保持响应式)
const updatedItems = [...(items.value ?? [])];
updatedItems[index] = {
...updatedItems[index],
...item,
updatedAt: new Date(), // 自动更新时间戳
};
items.value = updatedItems; // 替换引用,触发 UI 更新
};
const removeItem = (id: number) => {
items.value = (items.value ?? []).filter((i) => i.id !== id); // <-- 替换数组引用
};
return { items, stats, isNameAvailable, addItem, removeItem };
return { items, stats, isNameAvailable, addItem, editItem, removeItem };
};
export const useItemsStore = createSharedComposable(_useItems);

View File

@@ -46,7 +46,7 @@
</div>
<div>
<ItemEditModal />
<ItemEditModal ref="itemEditModal" />
</div>
</div>
@@ -55,6 +55,14 @@
:data="items"
:columns="itemColumns"
>
<template #select-cell="{ row }">
<UCheckbox
:model-value="row.getIsSelected()"
@update:model-value="(value: boolean | 'indeterminate') => row.toggleSelected(!!value)"
aria-label="Select row"
/>
</template>
<template #name-cell="{ row }">
<div class="flex items-center gap-3">
<UAvatar
@@ -110,12 +118,15 @@
import type { TableColumn, DropdownMenuItem } from "@nuxt/ui";
import type { Row } from "@tanstack/vue-table";
const UCheckbox = resolveComponent("UCheckbox");
const UBadge = resolveComponent("UBadge");
const UAvatar = resolveComponent("UAvatar");
const toast = useToast();
const { items, stats } = useItemsStore();
const itemEditModal = ref<any>(null);
const deleteModal = reactive<{
open: boolean;
selectedItem: Item | null;
@@ -155,6 +166,18 @@ const statistics = [
];
const itemColumns: TableColumn<Item>[] = [
{
id: "select",
header: ({ table }) =>
h(UCheckbox, {
modelValue: table.getIsSomePageRowsSelected()
? "indeterminate"
: table.getIsAllPageRowsSelected(),
"onUpdate:modelValue": (value: boolean | "indeterminate") =>
table.toggleAllPageRowsSelected(!!value),
ariaLabel: "Select all",
}),
},
{
accessorKey: "id",
header: "#",
@@ -182,8 +205,10 @@ function getRowItems(row: Row<Item>): DropdownMenuItem[] {
color: "primary",
icon: "lucide:pencil-line",
onSelect() {
itemEditModal.value?.openModal(row.original);
toast.add({
title: `Editing ${row.original.name}...`,
title: `编辑 ${row.original.name}`,
description: "已打开编辑模态框",
color: "warning",
icon: "lucide:pencil-line",
});