关于页面缓存
页面缓存需求:
- 组件间传参缓存
- 子页面浏览记录缓存
- 关闭浏览器,再次登录回到之前的页面
1、组件间传参缓存用的keepalive
结合router
,缓存页面
在app.vue
中,使用$route.meta
的keepAlive
属性缓存需要的页面:
<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/false
const router = new Router({
mode: "history",
base: process.env.BASE_URL,
routes: [
{
path: "list",
name: "list",
meta: { title: "列表页", type: "list", keepAlive: false },
component: () =>
import(/* webpackChunkName: "list" */ "./view/list") //模块化打包,速度更快,包更小
},
{
path: "addList",
name: "addList",
meta: { title: "添加列表页", type: "addList", keepAlive: true},
component: () =>
import(/* webpackChunkName: "addList" */ "./view/addList")
},
]
})
注:在keepAlive组件激活状态下,使用了keepAlive组件的页面,第二次渲染将不会再执行activated生命周期
2、子页面浏览缓存用的vuex
缓存子页面URL,在项目中记录用户浏览记录,一般用于后退操作;一级页面下有多个子页面,子页面之间可以互相跳转,有些子页面后退只能去固定的页面,而localstorage
缓存的只是上一页面不符合需求,所以就使用了vuex
缓存。
3、关闭浏览器再次打开缓存用的localstorage
跳转页面时,缓存当前页面URL
到localstorage
,下次打开打开浏览器再登录时,直接跳转到记录的页面
//在main.js的router.beforeEach中做判断和缓存操作
router.beforeEach((to, from, next) => {
if (to.path !== "/login/login" ) { //不缓存登录页
window.localStorage.setItem("login_jump_url", to.path);
}
next();
}