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>
相关推荐
代码煮茶12 小时前
Pinia 状态管理实战 | 从 0 到 1 搭建 Vue3 项目状态层(附模块化 / 持久化)
前端·vue.js
angerdream12 小时前
https://editor.csdn.net/md/?articleId=159120195
javascript·vue.js
siger12 小时前
花式玩转TypeScript类型-我使用swagger的描述文件自动生成类型的npm包供前端使用
前端·typescript·npm
用户812748281512012 小时前
kill只是杀进程吗?信号部分实战--系统开发必学linux基础知识
前端
Ferries12 小时前
工作五年前端,终于靠OpenClaw拥有了专属个人网站
前端·ai编程
敲敲敲敲暴你脑袋12 小时前
穷鬼快乐AI工具Ollama
javascript·人工智能·ollama
WayneX12 小时前
Vue 3 + TypeScript + Vite 组件库搭建,自助式生成相应组件文档
前端·javascript·vue.js
SunnyJingJing12 小时前
2026 css自适应实现布局方式
前端
贾铭12 小时前
如何实现一个网页版的剪映(四)使用插件化思维创建pixi绘制画布(转场/滤镜)
前端·javascript
kgduu12 小时前
js之xml处理
xml·前端·javascript