整理之后发现vue3的keep-alive和vue2相差也不是太大,重点是写法改变了
Vuex4安装:npm install vuex@4
1、App.vue
<template>
<router-view v-slot="{ Component }">
<keep-alive :include="includeList">
<component :is="Component"></component>
</keep-alive>
</router-view>
</template>
<script lang="ts">
import { defineComponent, computed } from "vue";
import { useStore } from 'vuex'
export default defineComponent({
name: "App",
components: {
},
setup(props) {
let store = useStore()
const includeList = computed(() => {
return store.state.includeList
})
// console.log('includeList',includeList);
return { includeList }
}
});
</script>
2、页面底部导航中的需要缓存的一级页面
<script lang="ts">
import { defineComponent, toRefs, reactive, getCurrentInstance, onActivated} from "vue";
import { useRouter, onBeforeRouteLeave} from "vue-router";
import MyTabbar from "@components/tabbar.vue";
import { Toast } from "vant";
import { useStore } from 'vuex'
export default defineComponent({
name: "Special",
components: {
MyTabbar,
},
setup() {
let store = useStore()
const datas = reactive({
tabsArr: [],
active: 0,
gcate_id: '',
bannerArr: []
})
const router = useRouter();
const { proxy }: any = getCurrentInstance();
let urls = proxy.$urls
// 离开-可以利用这个触发删除页面缓存操作
onBeforeRouteLeave((to: any, from: any, next: any) => {
console.log('Leave-to', to);
console.log('Leave-from', from);
if (from.name === 'Special') {
store.commit('setInclude', 'Special')
// store.commit('delInclude', 'Special')
}
next()
})
// keep-alive
onActivated(() => {
console.log('onActivated');
// 获取分类
proxy.$axios.get('getgcate').then((res: any) => {
if (res.data.code == 0) {
datas.tabsArr = res.data.result
datas.gcate_id = res.data.result[0].gcate_id;
// getList()
} else {
Toast(res.data.msg)
}
})
})
return {
...toRefs(datas),
urls,
store
};
},
});
</script>
3、vuex代码-index.ts
import { createStore } from "vuex";
export default createStore({
state: {
includeList: ["Home", "Special"], // 开始就缓存两个底部导航
},
mutations: {
getInclude(state: any, data: any) {
state.includeList = data;
},
//插入缓存数组
setInclude(state: any, data: any) {
var index = state.includeList.indexOf(data);
if (index == -1) {
state.includeList.push(data);
}
},
//删除对应缓存字段
delInclude(state: any, data: any) {
var index = state.includeList.indexOf(data);
if (index > -1) {
state.includeList.splice(index, 1);
}
},
},
actions: {
},
modules: {},
});
4、二级页面需要缓存
// 假设二级页面name为“detail”,下一个页面为“settle”
// 流程,当“detail”页面前往下一个指定页面为“settle”时,缓存“detail”页面,否则就删除此缓存页面
setup(){
// 离开
onBeforeRouteLeave((to: any, from: any, next: any) => {
if (to.path === 'settle') {
store.commit('setInclude', 'detail')
}else{
store.commit('delInclude', 'detail')
}
next()
})
}
使用上述这个keep-alive+vuex方法,可以更加灵活的缓存页面,想缓存哪个就缓存哪个,不要就删除缓存。
创作不易,喜欢的点个赞吧!转发请经过博主允许再转发谢谢!