fix(ui): ensure table updates correctly on data changes
The UTable component was not reliably updating when items were added, edited, or removed due to a reactivity issue. This commit resolves the problem by forcing the table to re-render when its data source
changes.
- A `watch` with `{ deep: true }` is now used to monitor the `items` array for any changes.
- A `tableKey` is incremented on each change and passed as a `:key` to `UTable`, triggering a re-mount.
Additionally, data handling has been made more robust:
- The localStorage serializer now gracefully handles parsing errors and ensures data integrity for dates and tags.
- Added null-safe access for tags in the table template to prevent rendering errors.
This commit is contained in:
@@ -15,21 +15,39 @@ const _useItems = () => {
|
|||||||
serializer: {
|
serializer: {
|
||||||
read: (v) => {
|
read: (v) => {
|
||||||
if (!v) return [];
|
if (!v) return [];
|
||||||
const parsed = JSON.parse(v);
|
try {
|
||||||
return parsed.map((item: any) => ({
|
const parsed = JSON.parse(v);
|
||||||
...item,
|
return (parsed ?? []).map((item: any) => ({
|
||||||
createdAt: new Date(item.createdAt),
|
...item,
|
||||||
updatedAt: new Date(item.updatedAt),
|
createdAt: item.createdAt ? new Date(item.createdAt) : new Date(),
|
||||||
}));
|
updatedAt: item.updatedAt ? new Date(item.updatedAt) : new Date(),
|
||||||
|
// ensure tags is an array or null
|
||||||
|
tags: item.tags
|
||||||
|
? Array.isArray(item.tags)
|
||||||
|
? item.tags
|
||||||
|
: String(item.tags)
|
||||||
|
.split(",")
|
||||||
|
.map((t: string) => t.trim())
|
||||||
|
: null,
|
||||||
|
}));
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to parse item-database from localStorage", err);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
write: (v) => {
|
||||||
|
try {
|
||||||
|
return JSON.stringify(v ?? []);
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to stringify item-database", err);
|
||||||
|
return "[]";
|
||||||
|
}
|
||||||
},
|
},
|
||||||
write: (v) => JSON.stringify(v),
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// 直接使用 stored(Ref<Item[]>)。模板会自动解包,其他逻辑也简单。
|
|
||||||
const items = stored; // Ref<Item[]>
|
const items = stored; // Ref<Item[]>
|
||||||
|
|
||||||
// 统计项使用 items.value
|
|
||||||
const stats = {
|
const stats = {
|
||||||
totalItems: computed(() => (items.value ?? []).length),
|
totalItems: computed(() => (items.value ?? []).length),
|
||||||
addedThisMonth: computed(() => {
|
addedThisMonth: computed(() => {
|
||||||
@@ -53,26 +71,31 @@ const _useItems = () => {
|
|||||||
!(items.value ?? []).some((item) => item.name === name);
|
!(items.value ?? []).some((item) => item.name === name);
|
||||||
|
|
||||||
const addItem = (item: Item) => {
|
const addItem = (item: Item) => {
|
||||||
items.value = [...(items.value ?? []), item]; // <-- 替换数组引用
|
items.value = [...(items.value ?? []), item];
|
||||||
|
console.debug("[addItem] new length:", (items.value ?? []).length);
|
||||||
};
|
};
|
||||||
|
|
||||||
const editItem = (item: Item) => {
|
const editItem = (item: Item) => {
|
||||||
const index = (items.value ?? []).findIndex((i) => i.id === item.id);
|
const index = (items.value ?? []).findIndex((i) => i.id === item.id);
|
||||||
if (index === -1) return; // 未找到则直接返回
|
if (index === -1) return;
|
||||||
|
|
||||||
// 生成一个新的数组(保持响应式)
|
|
||||||
const updatedItems = [...(items.value ?? [])];
|
const updatedItems = [...(items.value ?? [])];
|
||||||
updatedItems[index] = {
|
updatedItems[index] = {
|
||||||
...updatedItems[index],
|
...updatedItems[index],
|
||||||
...item,
|
...item,
|
||||||
updatedAt: new Date(), // 自动更新时间戳
|
updatedAt: new Date(),
|
||||||
};
|
};
|
||||||
|
items.value = updatedItems;
|
||||||
items.value = updatedItems; // 替换引用,触发 UI 更新
|
console.debug("[editItem] updated id:", item.id);
|
||||||
};
|
};
|
||||||
|
|
||||||
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);
|
||||||
|
console.debug(
|
||||||
|
"[removeItem] removed id:",
|
||||||
|
id,
|
||||||
|
"new length:",
|
||||||
|
(items.value ?? []).length
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
return { items, stats, isNameAvailable, addItem, editItem, removeItem };
|
return { items, stats, isNameAvailable, addItem, editItem, removeItem };
|
||||||
|
|||||||
@@ -1,10 +1,5 @@
|
|||||||
<template>
|
<template>
|
||||||
<div>
|
<div>
|
||||||
<!-- <UPageHero
|
|
||||||
title="智能物品管理系统"
|
|
||||||
description="专业的物品数据库管理工具,支持图片记录、CSV导出和历史价格追踪"
|
|
||||||
headline="New release"
|
|
||||||
/> -->
|
|
||||||
<main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
<main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||||
<!-- 统计 -->
|
<!-- 统计 -->
|
||||||
<div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
|
<div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
|
||||||
@@ -50,9 +45,11 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- 给 UTable 一个 key(tableKey)用于在需要时强制重挂载 -->
|
||||||
<UTable
|
<UTable
|
||||||
|
:key="tableKey"
|
||||||
v-model:global-filter="globalFilter"
|
v-model:global-filter="globalFilter"
|
||||||
:data="items"
|
:data="itemsList"
|
||||||
:columns="itemColumns"
|
:columns="itemColumns"
|
||||||
>
|
>
|
||||||
<template #select-cell="{ row }">
|
<template #select-cell="{ row }">
|
||||||
@@ -78,11 +75,16 @@
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<!-- tags 空值兜底,并加 key 避免重复 key 警告 -->
|
||||||
<template #tags-cell="{ row }">
|
<template #tags-cell="{ row }">
|
||||||
<div class="flex gap-2">
|
<div class="flex gap-2">
|
||||||
<UBadge v-for="tag in row.original.tags" variant="subtle">{{
|
<UBadge
|
||||||
tag
|
v-for="(tag, idx) in row.original.tags ?? []"
|
||||||
}}</UBadge>
|
:key="`${row.original.id}-tag-${idx}`"
|
||||||
|
variant="subtle"
|
||||||
|
>
|
||||||
|
{{ tag }}
|
||||||
|
</UBadge>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -115,6 +117,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script lang="ts" setup>
|
<script lang="ts" setup>
|
||||||
|
import { computed, ref, reactive, watch } from "vue";
|
||||||
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";
|
||||||
|
|
||||||
@@ -127,16 +130,34 @@ const { items, stats } = useItemsStore();
|
|||||||
|
|
||||||
const itemEditModal = ref<any>(null);
|
const itemEditModal = ref<any>(null);
|
||||||
|
|
||||||
const deleteModal = reactive<{
|
const deleteModal = reactive<{ open: boolean; selectedItem: Item | null }>({
|
||||||
open: boolean;
|
|
||||||
selectedItem: Item | null;
|
|
||||||
}>({
|
|
||||||
open: false,
|
open: false,
|
||||||
selectedItem: null,
|
selectedItem: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
const globalFilter = ref<string>("");
|
const globalFilter = ref<string>("");
|
||||||
|
|
||||||
|
// --- computed 包装,保证传给 UTable 的始终是响应式且值随 items 变化
|
||||||
|
const itemsList = computed(() => items.value ?? []);
|
||||||
|
|
||||||
|
// --- 强制表格重挂载的 key(当 items 改变时递增)
|
||||||
|
const tableKey = ref(0);
|
||||||
|
// 深度监听 items(数组)变化:每次 items 内容或引用变化都让 tableKey++,从而触发 UTable 重新挂载
|
||||||
|
watch(
|
||||||
|
items,
|
||||||
|
() => {
|
||||||
|
tableKey.value += 1;
|
||||||
|
// Console debug(运行时可在浏览器控制台查看)
|
||||||
|
console.debug(
|
||||||
|
"[items watch] tableKey ->",
|
||||||
|
tableKey.value,
|
||||||
|
"items.length ->",
|
||||||
|
(items.value ?? []).length
|
||||||
|
);
|
||||||
|
},
|
||||||
|
{ deep: true }
|
||||||
|
);
|
||||||
|
|
||||||
// 统计
|
// 统计
|
||||||
const statistics = [
|
const statistics = [
|
||||||
{
|
{
|
||||||
@@ -221,7 +242,7 @@ function getRowItems(row: Row<Item>): DropdownMenuItem[] {
|
|||||||
icon: "lucide:trash-2",
|
icon: "lucide:trash-2",
|
||||||
onSelect() {
|
onSelect() {
|
||||||
deleteModal.selectedItem = row.original;
|
deleteModal.selectedItem = row.original;
|
||||||
deleteModal.open = true; // 👈 打开 Modal!
|
deleteModal.open = true;
|
||||||
toast.add({
|
toast.add({
|
||||||
title: `Deleting ${row.original.name}...`,
|
title: `Deleting ${row.original.name}...`,
|
||||||
color: "error",
|
color: "error",
|
||||||
|
|||||||
Reference in New Issue
Block a user