参考 https://github.com/vuejs/core/pull/4339 自定义组件封装keep-alive

This commit is contained in:
liangzhiyuan001 2022-09-15 14:54:26 +08:00
parent d1d71355d6
commit 7217ef5a56
2 changed files with 40 additions and 9 deletions

View File

@ -1,27 +1,48 @@
<template>
<section class="app-main">
<router-view v-slot="{ Component }">
<router-view v-slot="{ Component, route }">
<transition name="fade-transform" mode="out-in">
<!-- <keep-alive :include="cachedViews"> -->
<component :is="Component" :key="key" />
<!-- </keep-alive> -->
<keep-alive :include="cachedViews">
<component :is="wrap(route, Component)" :key="route.fullPath" />
</keep-alive>
</transition>
</router-view>
</section>
</template>
<script>
import { defineComponent } from 'vue';
import { defineComponent, h } from 'vue';
import store from '@/store';
import { mapState } from 'pinia';
export default defineComponent({
name: 'AppMain',
computed: {
...mapState(store.tagsView, ['wrapperMap']),
cachedViews() {
return store.tagsView().cachedViews;
},
key() {
return this.$route.path;
}
},
methods: {
// keep-alivecomponentname.
wrap(route, component) {
let wrapper;
//
// .
// keep-alive include .
const wrapperName = route.name;
if (this.wrapperMap.has(wrapperName)) {
wrapper = this.wrapperMap.get(wrapperName);
} else {
wrapper = {
name: wrapperName,
render() {
return h('div', { className: 'vaf-page-wrapper' }, component);
}
};
this.wrapperMap.set(wrapperName, wrapper);
}
return h(wrapper);
}
}
});

View File

@ -2,7 +2,8 @@ import { defineStore } from 'pinia';
const getDefaultState = () => ({
visitedViews: [],
cachedViews: []
cachedViews: [],
wrapperMap: new Map()
});
const getters = {};
@ -41,6 +42,9 @@ const actions = {
delCachedView(view) {
const index = this.cachedViews.indexOf(view.name);
index > -1 && this.cachedViews.splice(index, 1);
if (this.wrapperMap.has(view.name)) {
this.wrapperMap.delete(view.name);
}
},
delOthersViews(view) {
@ -60,6 +64,11 @@ const actions = {
// if index = -1, there is no cached tags
this.cachedViews = [];
}
this.wrapperMap.forEach((value, key) => {
if (view.name !== key) {
this.wrapperMap.delete(key);
}
});
},
delAllViews() {
@ -73,6 +82,7 @@ const actions = {
},
delAllCachedViews() {
this.cachedViews = [];
this.wrapperMap.clear();
},
updateVisitedView(view) {