feat(item): add delete functionality

This commit introduces the ability to delete items. A new `ItemDeleteModal` component provides a confirmation step
before removal.

- Adds a 'Delete' option to the action menu in the items table.
- Refactors the `useItems` composable to ensure reactivity with `useLocalStorage` by creating new array references on
add/remove operations.
- Renames `AddModal` to `EditModal` to better align with its future role in both adding and editing items.
This commit is contained in:
xiaomai
2025-10-14 10:43:23 +08:00
parent e05c41eb07
commit 675704e4da
5 changed files with 109 additions and 30 deletions

View File

@@ -1,6 +1,5 @@
import { useLocalStorage, createSharedComposable } from "@vueuse/core";
// 类型定义
export type Item = {
id: number;
name: string;
@@ -12,9 +11,10 @@ export type Item = {
};
const _useItems = () => {
const items = useLocalStorage<Item[]>("item-database", [], {
const stored = useLocalStorage<Item[]>("item-database", [], {
serializer: {
read: (v) => {
if (!v) return [];
const parsed = JSON.parse(v);
return parsed.map((item: any) => ({
...item,
@@ -26,34 +26,37 @@ const _useItems = () => {
},
});
// 直接使用 storedRef<Item[]>)。模板会自动解包,其他逻辑也简单。
const items = stored; // Ref<Item[]>
// 统计项使用 items.value
const stats = {
totalItems: computed(() => items.value.length),
totalItems: computed(() => (items.value ?? []).length),
addedThisMonth: computed(() => {
const now = new Date();
const thisMonth = now.getMonth();
const thisYear = now.getFullYear();
let count = 0;
for (const item of items.value) {
const date = item.createdAt;
if (date.getMonth() === thisMonth && date.getFullYear() === thisYear) {
count++;
}
}
return count;
return (items.value ?? []).filter(
(item) =>
item.createdAt.getMonth() === thisMonth &&
item.createdAt.getFullYear() === thisYear
).length;
}),
latestId: computed(
() => (items.value[items.value.length - 1]?.id ?? 0) + 1
() => (items.value?.[items.value.length - 1]?.id ?? 0) + 1
),
};
const isNameAvailable = (name: string) =>
!items.value.some((item) => item.name === name);
!(items.value ?? []).some((item) => item.name === name);
const addItem = (item: Item) => items.value.push(item);
const addItem = (item: Item) => {
items.value = [...(items.value ?? []), item]; // <-- 替换数组引用
};
const removeItem = (id: number) =>
(items.value = items.value.filter((i) => i.id !== id));
const removeItem = (id: number) => {
items.value = (items.value ?? []).filter((i) => i.id !== id); // <-- 替换数组引用
};
return { items, stats, isNameAvailable, addItem, removeItem };
};