keep-alive、localstorage、vuex缓存页面访问记录

关于页面缓存

页面缓存需求:

  • 组件间传参缓存
  • 子页面浏览记录缓存
  • 关闭浏览器,再次登录回到之前的页面

1、组件间传参缓存用的keepalive
结合router,缓存页面
app.vue中,使用$route.metakeepAlive属性缓存需要的页面:

<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
跳转页面时,缓存当前页面URLlocalstorage,下次打开打开浏览器再登录时,直接跳转到记录的页面

//在main.js的router.beforeEach中做判断和缓存操作
router.beforeEach((to, from, next) => {
	if (to.path !== "/login/login" ) { //不缓存登录页
	    window.localStorage.setItem("login_jump_url", to.path);
	  }
  next();
}
发布了27 篇原创文章 · 获赞 21 · 访问量 4594

猜你喜欢

转载自blog.csdn.net/weixin_43997143/article/details/91044734
今日推荐