app.vue <div id="app"> <router-view v-slot="{ Component }"> <keep-alive :include ="keepalive.mainAliveList"> <component :is="Component"/> </keep-alive> </router-view> </div>
layout.vue <el-container class="layout"> <Header /> <div class="mix"> <Side /> <div class="main"> <router-view v-slot="{ Component }"> <keep-alive :include ="keepalive.list"> <component :is="Component"/> </keep-alive> </router-view> </div> </div> </el-container>
books-setting.vue 需要缓存的组件,router:BooksSetting const keepalive = keepaliveList(); // store存储 需求:BooksSetting进入BookImg,从BookImg页面回到BooksSetting页面BooksSetting需要缓存 进入BooksSetting页面时先将缓存组件放到keeplive中,缓存组件,进入BookImg页面时,watch可以监听到路由,进入其他页面则将keepalive清空 watch( () => route.name, (newValue, oldValue) => { // 缓存后的组件,可以监听到每次的route变化 if (newValue === 'BooksSetting' || newValue === 'BookImg') { if (keepalive.list.indexOf('books-setting') < 0) { keepalive.setList(['books-setting']); } } else { keepalive.setList(['']); } }, { immediate: true } );