vue keep-alive
keep-alive 会把其包裹的所有组件都缓存起来
<div id="app"> <keep-alive :include="include"> <router-view v-if="$route.meta.keepAlive" /> </keep-alive> <router-view v-if="!$route.meta.keepAlive" /> </div>
include 参数 类型 Array
字符串或正则表达式, 只有名称匹配的组件会被缓存
app.vue***
export default { name: "app", data: () => ({ include: [] }), watch: { $route(to, from) { //如果 要 to(进入) 的页面是需要 keepAlive 缓存的,把 name push 进 include数组 if (to.meta.keepAlive) { !this.include.includes(to.name) && this.include.push(to.name); } //如果 要 form(离开) 的页面是 keepAlive缓存的, //再根据 deepth 来判断是前进还是后退 //如果是后退 if (from.meta.keepAlive && to.meta.deepth < from.meta.deepth) { var index = this.include.indexOf(from.name); index !== -1 && this.include.splice(index, 1); } } } }
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const constantRoutes = [ { path: '/', name: "home", component: () => import("@/page/home/index"), meta: { title: "首页", deepth: 0.5 } }, { path: '/list', name: "list", component: () => import("@/page/msg/list"), meta: { title: "消息列表", deepth: 1, keepAlive: true //需要被缓存 } }, { path: '/msg', name: "msg", component: () => import("@/page/msg/index"), meta: { title: "消息", deepth: } }, ] const router = new VueRouter({ routes: constantRoutes }) export default router
备注: 我们包裹的组件都有字的名字(name)