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: {
|
||||
read: (v) => {
|
||||
if (!v) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(v);
|
||||
return parsed.map((item: any) => ({
|
||||
return (parsed ?? []).map((item: any) => ({
|
||||
...item,
|
||||
createdAt: new Date(item.createdAt),
|
||||
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[]>
|
||||
|
||||
// 统计项使用 items.value
|
||||
const stats = {
|
||||
totalItems: computed(() => (items.value ?? []).length),
|
||||
addedThisMonth: computed(() => {
|
||||
@@ -53,26 +71,31 @@ const _useItems = () => {
|
||||
!(items.value ?? []).some((item) => item.name === name);
|
||||
|
||||
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 index = (items.value ?? []).findIndex((i) => i.id === item.id);
|
||||
if (index === -1) return; // 未找到则直接返回
|
||||
|
||||
// 生成一个新的数组(保持响应式)
|
||||
if (index === -1) return;
|
||||
const updatedItems = [...(items.value ?? [])];
|
||||
updatedItems[index] = {
|
||||
...updatedItems[index],
|
||||
...item,
|
||||
updatedAt: new Date(), // 自动更新时间戳
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
items.value = updatedItems; // 替换引用,触发 UI 更新
|
||||
items.value = updatedItems;
|
||||
console.debug("[editItem] updated id:", item.id);
|
||||
};
|
||||
|
||||
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 };
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
<template>
|
||||
<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">
|
||||
<!-- 统计 -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
|
||||
@@ -50,9 +45,11 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 给 UTable 一个 key(tableKey)用于在需要时强制重挂载 -->
|
||||
<UTable
|
||||
:key="tableKey"
|
||||
v-model:global-filter="globalFilter"
|
||||
:data="items"
|
||||
:data="itemsList"
|
||||
:columns="itemColumns"
|
||||
>
|
||||
<template #select-cell="{ row }">
|
||||
@@ -78,11 +75,16 @@
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- tags 空值兜底,并加 key 避免重复 key 警告 -->
|
||||
<template #tags-cell="{ row }">
|
||||
<div class="flex gap-2">
|
||||
<UBadge v-for="tag in row.original.tags" variant="subtle">{{
|
||||
tag
|
||||
}}</UBadge>
|
||||
<UBadge
|
||||
v-for="(tag, idx) in row.original.tags ?? []"
|
||||
:key="`${row.original.id}-tag-${idx}`"
|
||||
variant="subtle"
|
||||
>
|
||||
{{ tag }}
|
||||
</UBadge>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -115,6 +117,7 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, ref, reactive, watch } from "vue";
|
||||
import type { TableColumn, DropdownMenuItem } from "@nuxt/ui";
|
||||
import type { Row } from "@tanstack/vue-table";
|
||||
|
||||
@@ -127,16 +130,34 @@ const { items, stats } = useItemsStore();
|
||||
|
||||
const itemEditModal = ref<any>(null);
|
||||
|
||||
const deleteModal = reactive<{
|
||||
open: boolean;
|
||||
selectedItem: Item | null;
|
||||
}>({
|
||||
const deleteModal = reactive<{ open: boolean; selectedItem: Item | null }>({
|
||||
open: false,
|
||||
selectedItem: null,
|
||||
});
|
||||
|
||||
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 = [
|
||||
{
|
||||
@@ -221,7 +242,7 @@ function getRowItems(row: Row<Item>): DropdownMenuItem[] {
|
||||
icon: "lucide:trash-2",
|
||||
onSelect() {
|
||||
deleteModal.selectedItem = row.original;
|
||||
deleteModal.open = true; // 👈 打开 Modal!
|
||||
deleteModal.open = true;
|
||||
toast.add({
|
||||
title: `Deleting ${row.original.name}...`,
|
||||
color: "error",
|
||||
|
||||
Reference in New Issue
Block a user