feat: 重构缓存逻辑,优化数据更新和清空缓存的实现
This commit is contained in:
@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { toRaw } from 'vue';
|
||||
const structuredClone = window.structuredClone || ((obj) => JSON.parse(JSON.stringify(obj)));
|
||||
|
||||
const K_INITIAL_CACHE = deepFreeze({
|
||||
@ -7,15 +8,19 @@ const K_INITIAL_CACHE = deepFreeze({
|
||||
hasMore: true,
|
||||
});
|
||||
const cache = structuredClone(K_INITIAL_CACHE);
|
||||
const updateCache = (newCache: typeof cache) =>
|
||||
Object.assign(cache, Object.fromEntries(Object.entries(newCache).map(([key, value]) => [key, toRaw(value)])));
|
||||
const clearCache = () => Object.assign(cache, structuredClone(K_INITIAL_CACHE));
|
||||
// XXX: 可以直接把 list 定义在这上面???
|
||||
</script>
|
||||
|
||||
<script setup lang="ts">
|
||||
defineOptions({
|
||||
beforeRouteEnter: (to, from) => {
|
||||
if (from.name !== 'InfiniteLoadingDetail') Object.assign(cache, structuredClone(K_INITIAL_CACHE)); // 如果来的页面不是详情页,清空缓存。
|
||||
if (from.name !== 'InfiniteLoadingDetail') clearCache(); // 如果来的页面不是详情页,清空缓存。
|
||||
},
|
||||
beforeRouteLeave: (to, from) => {
|
||||
if (to.name !== 'InfiniteLoadingDetail') Object.assign(cache, structuredClone(K_INITIAL_CACHE)); // 如果去的页面不是详情页,清空缓存。
|
||||
if (to.name !== 'InfiniteLoadingDetail') clearCache(); // 如果去的页面不是详情页,清空缓存。
|
||||
},
|
||||
});
|
||||
|
||||
@ -37,11 +42,7 @@ const loadData = async (page: number) => {
|
||||
const data = await response.json();
|
||||
list.value = list.value.concat(data);
|
||||
const hasMore = list.value.length < 5;
|
||||
{
|
||||
cache.page = page;
|
||||
cache.list = toRaw(list.value);
|
||||
cache.hasMore = hasMore;
|
||||
}
|
||||
updateCache({ page: page + lastCache.page, list: list.value, hasMore });
|
||||
return { hasMore };
|
||||
};
|
||||
</script>
|
||||
|
Reference in New Issue
Block a user