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:
@@ -1,11 +1,19 @@
|
|||||||
<template>
|
<template>
|
||||||
<UModal v-model:open="open" title="新增物品" description="新增一件新的物品">
|
<UModal
|
||||||
<UButton label="新增" icon="lucide:plus" />
|
v-model:open="open"
|
||||||
|
:title="isEditMode ? '编辑物品' : '新增物品'"
|
||||||
|
:description="isEditMode ? '修改现有物品信息' : '新增一件新的物品'"
|
||||||
|
>
|
||||||
|
<UButton
|
||||||
|
label="新增"
|
||||||
|
icon="lucide:plus"
|
||||||
|
@click="openModal()"
|
||||||
|
/>
|
||||||
|
|
||||||
<template #body>
|
<template #body>
|
||||||
<UForm
|
<UForm
|
||||||
ref="itemForm"
|
ref="itemForm"
|
||||||
:schema="itemSchema"
|
:schema="formSchema"
|
||||||
:state="itemState"
|
:state="itemState"
|
||||||
@submit="onSubmit"
|
@submit="onSubmit"
|
||||||
class="space-y-4"
|
class="space-y-4"
|
||||||
@@ -59,7 +67,7 @@
|
|||||||
@click="open = false"
|
@click="open = false"
|
||||||
/>
|
/>
|
||||||
<UButton
|
<UButton
|
||||||
label="创建"
|
:label="isEditMode ? '保存修改' : '创建'"
|
||||||
color="primary"
|
color="primary"
|
||||||
variant="solid"
|
variant="solid"
|
||||||
@click="itemForm.submit()"
|
@click="itemForm.submit()"
|
||||||
@@ -75,20 +83,34 @@ import * as z from "zod";
|
|||||||
|
|
||||||
const itemForm = ref();
|
const itemForm = ref();
|
||||||
const open = ref<boolean>(false);
|
const open = ref<boolean>(false);
|
||||||
const toast = useToast();
|
const isEditMode = ref<boolean>(false);
|
||||||
const { stats, isNameAvailable, addItem } = useItemsStore();
|
const currentId = ref<number | null>(null);
|
||||||
|
|
||||||
const itemSchema = z.object({
|
const toast = useToast();
|
||||||
name: z
|
const { stats, isNameAvailable, addItem, editItem, items } = useItemsStore();
|
||||||
.string()
|
|
||||||
.min(1, "名称不能为空")
|
// 🧩 基础校验(动态 schema)
|
||||||
.refine(isNameAvailable, "该名称已被占用,请更换一个"),
|
const baseSchema = z.object({
|
||||||
|
name: z.string().min(1, "名称不能为空"),
|
||||||
imageUrl: z.string().nullable().optional(),
|
imageUrl: z.string().nullable().optional(),
|
||||||
description: z.string().nullable().optional(),
|
description: z.string().nullable().optional(),
|
||||||
tags: 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>({
|
const itemState = reactive<ItemSchema>({
|
||||||
name: "",
|
name: "",
|
||||||
@@ -97,8 +119,52 @@ const itemState = reactive<ItemSchema>({
|
|||||||
tags: null,
|
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 onSubmit = async (event: FormSubmitEvent<ItemSchema>) => {
|
||||||
const item: Item = {
|
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(),
|
||||||
|
};
|
||||||
|
|
||||||
|
editItem(updatedItem);
|
||||||
|
toast.add({
|
||||||
|
title: "已保存修改",
|
||||||
|
description: `${event.data.name} 的信息已更新`,
|
||||||
|
color: "success",
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// ✅ 新增模式
|
||||||
|
const newItem: Item = {
|
||||||
id: stats.latestId.value,
|
id: stats.latestId.value,
|
||||||
name: event.data.name,
|
name: event.data.name,
|
||||||
imageUrl: event.data.imageUrl,
|
imageUrl: event.data.imageUrl,
|
||||||
@@ -108,16 +174,19 @@ const onSubmit = async (event: FormSubmitEvent<ItemSchema>) => {
|
|||||||
updatedAt: new Date(),
|
updatedAt: new Date(),
|
||||||
};
|
};
|
||||||
|
|
||||||
// TODO: Check is add or edit
|
addItem(newItem);
|
||||||
addItem(item);
|
|
||||||
|
|
||||||
toast.add({
|
toast.add({
|
||||||
title: "成功",
|
title: "成功",
|
||||||
description: `${event.data.name} 已被添加到数据库中`,
|
description: `${event.data.name} 已添加到数据库中`,
|
||||||
color: "success",
|
color: "success",
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
open.value = false;
|
open.value = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// expose method so parent can call modal.openModal(item)
|
||||||
|
defineExpose({ openModal });
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style></style>
|
<style></style>
|
||||||
|
|||||||
@@ -42,9 +42,11 @@ const _useItems = () => {
|
|||||||
item.createdAt.getFullYear() === thisYear
|
item.createdAt.getFullYear() === thisYear
|
||||||
).length;
|
).length;
|
||||||
}),
|
}),
|
||||||
latestId: computed(
|
latestId: computed(() => {
|
||||||
() => (items.value?.[items.value.length - 1]?.id ?? 0) + 1
|
const arr = items.value ?? [];
|
||||||
),
|
if (arr.length === 0) return 1;
|
||||||
|
return Math.max(...arr.map((i) => i.id)) + 1;
|
||||||
|
}),
|
||||||
};
|
};
|
||||||
|
|
||||||
const isNameAvailable = (name: string) =>
|
const isNameAvailable = (name: string) =>
|
||||||
@@ -54,11 +56,26 @@ const _useItems = () => {
|
|||||||
items.value = [...(items.value ?? []), item]; // <-- 替换数组引用
|
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) => {
|
const removeItem = (id: number) => {
|
||||||
items.value = (items.value ?? []).filter((i) => i.id !== id); // <-- 替换数组引用
|
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);
|
export const useItemsStore = createSharedComposable(_useItems);
|
||||||
|
|||||||
@@ -46,7 +46,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<ItemEditModal />
|
<ItemEditModal ref="itemEditModal" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -55,6 +55,14 @@
|
|||||||
:data="items"
|
:data="items"
|
||||||
:columns="itemColumns"
|
: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 }">
|
<template #name-cell="{ row }">
|
||||||
<div class="flex items-center gap-3">
|
<div class="flex items-center gap-3">
|
||||||
<UAvatar
|
<UAvatar
|
||||||
@@ -110,12 +118,15 @@
|
|||||||
import type { TableColumn, DropdownMenuItem } from "@nuxt/ui";
|
import type { TableColumn, DropdownMenuItem } from "@nuxt/ui";
|
||||||
import type { Row } from "@tanstack/vue-table";
|
import type { Row } from "@tanstack/vue-table";
|
||||||
|
|
||||||
|
const UCheckbox = resolveComponent("UCheckbox");
|
||||||
const UBadge = resolveComponent("UBadge");
|
const UBadge = resolveComponent("UBadge");
|
||||||
const UAvatar = resolveComponent("UAvatar");
|
const UAvatar = resolveComponent("UAvatar");
|
||||||
const toast = useToast();
|
const toast = useToast();
|
||||||
|
|
||||||
const { items, stats } = useItemsStore();
|
const { items, stats } = useItemsStore();
|
||||||
|
|
||||||
|
const itemEditModal = ref<any>(null);
|
||||||
|
|
||||||
const deleteModal = reactive<{
|
const deleteModal = reactive<{
|
||||||
open: boolean;
|
open: boolean;
|
||||||
selectedItem: Item | null;
|
selectedItem: Item | null;
|
||||||
@@ -155,6 +166,18 @@ const statistics = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
const itemColumns: TableColumn<Item>[] = [
|
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",
|
accessorKey: "id",
|
||||||
header: "#",
|
header: "#",
|
||||||
@@ -182,8 +205,10 @@ function getRowItems(row: Row<Item>): DropdownMenuItem[] {
|
|||||||
color: "primary",
|
color: "primary",
|
||||||
icon: "lucide:pencil-line",
|
icon: "lucide:pencil-line",
|
||||||
onSelect() {
|
onSelect() {
|
||||||
|
itemEditModal.value?.openModal(row.original);
|
||||||
toast.add({
|
toast.add({
|
||||||
title: `Editing ${row.original.name}...`,
|
title: `编辑 ${row.original.name}`,
|
||||||
|
description: "已打开编辑模态框。",
|
||||||
color: "warning",
|
color: "warning",
|
||||||
icon: "lucide:pencil-line",
|
icon: "lucide:pencil-line",
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user