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>
相关推荐
慕斯-ing8 分钟前
利用Vue编写一个“计数器”
前端·vue.js·经验分享
暗暗那29 分钟前
【腾讯前端面试】纯css画图形
前端·css·面试
yqcoder30 分钟前
Node 服务器数据响应类型处理
运维·服务器·前端·javascript·node.js
�时过境迁,物是人非30 分钟前
C#中的if判断语句详解
java·前端·c#
shangaoo38 分钟前
XML DOM 节点信息
xml·java·前端
大模型铲屎官1 小时前
深入剖析 HTML5 新特性:语义化标签和表单控件完全指南
前端·html·编程·html5·语义化标签·表单控件
brahmsjiang1 小时前
React中的JavaScript语法
前端·javascript·react.js
prince_zxill1 小时前
深入探索Vue 3组合式API
前端·javascript·网络·vue.js·前端框架
uperficialyu1 小时前
20250108慧能科技前端面试
前端
学问小小谢2 小时前
第28节课:前端项目实战—从需求分析到开发流程的全方位指南
前端·网络·安全·web安全·性能优化·html5·需求分析