vue3(setup) keep-alive 列表页跳转详情缓存,跳转其它更新

app.vue(或其它入口页)使用keep-alive的include动态设置缓存

注意:有嵌套的页面需要在嵌套内部的router-view上添加keep-alive

javascript 复制代码
<template>
    <router-view v-slot="{ Component}">
        <keep-alive :include="cacheList">
          <component :is="Component" />
        </keep-alive>
     </router-view>
</template>
<script setup lang="ts">
import { cacheStore } from "@/stores";
const store = cacheStore();
// 在store中定义一个cacheList用在存放缓存页面
const cacheList = computed(() => {
    return store.cacheList;
});
</script>

stores的index.ts:使用pinia调控缓存页面的数组

javascript 复制代码
import { defineStore } from "pinia";
import { cacheState } from './types';
const cacheStore = defineStore("cache", {
    state: (): cacheState => ({
        cacheList:[] // keep-alive缓存列表
    }),
    actions: {
        pushCaches(item:string) {
            let set = new Set(this.cacheList);
            set.add(item);
            this.cacheList = Array.from(set);
        },
        popCaches(item:string) {
            let set = new Set(this.cacheList);
            if (set.has(item)) {
                set.delete(item);
            }
            this.cacheList = Array.from(set);
        },
    },
});
export default cacheStore;

list.vue(列表页)

注意:vue3的setup模式使用defineOptions为页面路由命名

javascript 复制代码
<script lang="ts" setup>
import { ref } from "vue";
import { onBeforeRouteLeave} from "vue-router";
import { cacheStore } from "@/stores";
const store = cacheStore();
//路由命名(非组件名)
defineOptions({ name: "list" });
//离开页面守卫
onBeforeRouteLeave((to, _from, next) => {
    // 若跳转的是详情页缓存本页面,否则清除本页缓存
    if (to.name === "detail") {
        store.pushCaches("list");
    } else {
        store.popCaches("list");
    }
    next();
});
</script>

detail.vue(详情页)

javascript 复制代码
<script lang="ts" setup>
//路由命名
defineOptions({ name: "detail" });
</script>
相关推荐
叶落阁主9 小时前
AntV npm 投毒复盘:一次公司私服缓存恶意包引发的账号封禁事件
前端·安全·npm
vaexu9 小时前
Android 定时提醒的终极防线:我是如何用“双保险机制”攻克后台保活的?
前端
小村儿9 小时前
连载11- Claude code 的 Agent Teams——当子 Agent 开始互相说话
前端·后端·ai编程
布吉岛的石头9 小时前
Java 程序员第 38 阶段:Embedding 向量缓存实战,减少重复向量化计算开销
java·缓存·embedding
潍坊老登10 小时前
关于 number类型从vue端传到golang后端是float而不是int的事
前端
茶底世界之下10 小时前
你的 Mac 里,藏着一支 AI 开发团队
前端·javascript
小白学大数据10 小时前
Playwright 爬虫:Python 爬取 JS 渲染的 JSP 网站
开发语言·javascript·爬虫·python·数据分析
不爱说话郭德纲10 小时前
出门在外收到任务,我用 TRAE SOLO 把电脑“叫醒”干活
前端·ai编程
前端Hardy10 小时前
这个前端动画库,火了!
前端·javascript
小林攻城狮10 小时前
Vite项目使用@turbodocx/html-to-docx报错问题排查与解决方案
前端·ai编程