vue keepalive
vue2
App.vue
<keep-alive>
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>
router.js
meta: {
keepAlive: true, //此组件需要被缓存
isBack: false
},
list.vue
beforeRouteEnter(to, from, next) {
if(from.name == 'classDetail') { //判断是从哪个路由过来的,若是detail页面不需要刷新获取新数据,直接用之前缓存的数据即可
to.meta.isBack = false;
}else{
to.meta.isBack = true;
}
next();
},
activated() {
if(this.$route.meta.isBack) {
// 如果isBack是false,表明需要获取新数据,否则就不再请求,直接使用缓存的数据
调接口,把之前created里面的写这里, 没有created生命周期
}
// 恢复成默认的false,避免isBack一直是true,导致下次无法获取数据
this.$route.meta.isBack = false
},
vue3
App.vue
<router-view v-slot="{Component}">
<keep-alive>
<component :is="Component" v-if="route.meta.keepAlive"/>
</keep-alive>
<component :is="Component" v-if="!route.meta.keepAlive"/>
</router-view>
router.js
meta: {
keepAlive: true,
isBack: false
},
//3里面vue-router没有beforeEnter,只能写在router.js里面了 或者写在setup外面用vue2的写法 或者用vue router next 的
onBeforeRouteUpdate 试试
beforeEnter: (to, from, next) => {
if (from.name == "articleDetail"){
to.meta.isBack = true;
}else{
to.meta.isBack = false;
}
next();
},l
list.vue
onActivated(() => {
if(!route.meta.isBack) {
调接口,把之前created里面的写这里, 没有created生命周期
}
route.meta.isBack = false
})
keeplive只能缓存一二级页面,keepalive缓存页面时要写在最近的routerview'上,否则失效
要想缓存三四级页面,百度