思路:在app.vue 中加入keepAlive,需要设置一个全局变量,来操控页面是否需要进行缓存
keepAlive重要属性: include:数组,放需要进行缓存的页面,默认缓存所有页面;exclude:数组,放不需要进行缓存的页面 且exclude的优先级 > include的优先级
1. 设置全局变量
在src文件夹下面新建utils
文件夹,在utils
里面新建index.js
文件,其内容如下
import { ref } from "vue";
export const excludes = ref([]);
//消除缓存
export function removeKeepAliveCache(instance) {
excludes.value.push(instance.type.name);
}
//增加缓存
export function resetKeepAliveCache(instance) {
excludes.value = excludes.value.filter((item) => item !== instance.type.name);
}
2. app.vue中代码
<router-view v-slot="{ Component }">
<keep-alive :include="include" :exclude="excludes">
<Component :is="Component"></Component>
</keep-alive>
</router-view>
<script setup >
import { excludes } from "@/utils";
const include = ["KeepAliveInput"]; //需要进行缓存的页面
</script>
3. 在需要缓存的页面中进行操作
<template>
<div class="page_container">
<div class="nav_bar">
<span class="back_btn" @click="router.back()"> < </span>
<span class="nav_title">KeepAliveInputPage</span>
</div>
<div class="mgt_50">keywords:<input v-model="keywords" type="text" /></div>
<div class="mgt_50">selectedResult:<input v-model="selectedRes" type="text" /></div>
<div class="bb_btn mgt_50" @click="toSelect">toSelectPage</div>
</div>
</template>
<script>
export default {
name: "KeepAliveInput",
};
</script>
<script setup>
import { getCurrentInstance,ref } from "vue";
import { onBeforeRouteLeave, useRouter } from "vue-router";
import { removeKeepAliveCache, resetKeepAliveCache } from "@/utils";
const router = useRouter();
const keywords = ref("");
const selectedRes = ref("");
const toSelect = () => {
router.push("KeepAliveSelect");
};
const instance = getCurrentInstance();
console.log(instance);
onBeforeRouteLeave((to, from) => {
// KeepAliveIndex 是本页面的上一级页面的name值
if (["KeepAliveIndex"].includes(to.name)) {
removeKeepAliveCache(instance);
} else {
resetKeepAliveCache(instance);
}
});
</script>
<style scoped></style>
详情请看:代码git地址