vue3的keep-alive和vue2很大不同,折腾很久。
App.vue代码
<script setup>
import {ref,watch} from 'vue'
import {useRouter } from 'vue-router';
const include = ref([])
const router = useRouter()
var from = ref(null)
watch(//这里和vue2有点区别
() => router.currentRoute.value,
(to) => {
console.log('to',to)
if (to.meta && to.meta.keepAlive) {
!include.value.includes(to.name) && include.value.push(to.name);
}
if (from.value && from.value.meta.keepAlive && to.meta.deepth < from.value.meta.deepth) {
var index = include.value.indexOf(from.value.name);
index !== -1 && include.value.splice(index, 1);
}
from.value = to
}
)
</script>
<template>
<div id="app">
<router-view v-slot="{ Component, route }">
<keep-alive :include="include">
<component :is="Component" :key="route.name" v-if="route.meta.keepAlive"></component>
</keep-alive>
<component :is="Component" :key="route.name" v-if="!route.meta.keepAlive" />
</router-view>
</div>
</template>
路由文件index.js
{
path:'/list',
name:'list',
component:listPage,
meta: {
keepAlive: true,
deepth:1
},
},
{
path:'/detail',
name:'detail',
component:Detail,
meta: {
keepAlive: true,
deepth:2
},
},
{
path:'/edit',
name:'edit',
component:edit,
meta: {
keepAlive: true,
deepth:3
},
},
具体页面ListPage.vue
安装一个插件npm install vite-plugin-vue-setup-extend --save,为了能在setup上定义组件名name
<script setup name='list'>
</script>