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>
相关推荐
xixixiLucky2 分钟前
配置Java Selenium Web自动化测试环境
java·前端·selenium
gregmankiw17 分钟前
第二个简单的SpringBoot和Vue前后端全栈的todoapp案例
前端·javascript·vue.js
我可是ikun啊43 分钟前
Redis经典面试题
数据库·redis·缓存
酷小洋1 小时前
Ajax基础
前端·ajax·okhttp
小妖6661 小时前
vue2 provide 后 inject 数据不是响应式的,不实时更新
java·服务器·前端
是代码侠呀2 小时前
HTTP 的发展史:从前端视角看网络协议的演进
前端·网络协议·http·开源·github·github star·github 加星
heyCHEEMS2 小时前
Vue 两种导航方式
前端·javascript·vue.js
我是哈哈hh2 小时前
【vue】vuex实现组件间数据共享 & vuex模块化编码 & 网络请求
前端·javascript·vue.js·前端框架·网络请求·vuex·模块化
想睡好2 小时前
圆角边框 盒子阴影 文字阴影
前端·css·html
fei_sun2 小时前
【数据结构】子串、前缀
java·前端·数据结构