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>
相关推荐
Python自动化直播18 分钟前
智能脚本批量管理拆开看:导入、导出、重写、试听
前端·python·ai·秒播
开开心心就好34 分钟前
发票信息录入太麻烦?离线工具一键转表格
运维·服务器·前端·pdf·ocr·maven·intellij-idea
এ慕ོ冬℘゜1 小时前
ES Promise.all/ Promise.race
前端·javascript·elasticsearch
Shaoshing2 小时前
缓存一致问题及常见解决方案
java·缓存
喜欢打篮球的普通人2 小时前
LLVM 前端与优化层:Clang 如何把 C 代码变成 IR
c语言·前端·状态模式
只睡四小时2 小时前
端侧推理:face-api.js 首屏 92% 是白下载的
开发语言·javascript·人脸识别·ecmascript·tensorflow.js·face-api.js·端侧推理
大文说跨境2 小时前
亚马逊多店铺用过多款指纹浏览器,说点长期用的实际感受
前端·网络
中屹指纹浏览器svip2 小时前
中屹指纹浏览器和普通 Chrome 有什么区别?
前端·chrome·中屹指纹浏览器
码士集团小青2 小时前
Redis 缓存击穿(失效)、缓存穿透、缓存雪崩怎么解决?
数据库·redis·缓存