首页
归档
笔记
树洞
搜索
友言

文章详情

Interesting People Record Interesting.

/ JavaScript / 文章详情

Vue项目单页面问题之:页面缓存

Sonder
2021-01-06
1963字
5分钟
浏览 (3.6k)

在手机端我们常常遇到这种问题,当我们从列表页进入详情页时,再返回到详情页后要记住当前的位置。但是由于路由做了一些处理,返回后就回到顶部了。现在就是处理这些问题!

1.App.vue

复制代码
<div id="app">
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive" />
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive" />
</div>

2.路由 router/index.js

需要缓存的路由页面路径

复制代码
   {
       path: '/list',
       name: 'list',
       component: () => import('@/views/buy/list'),
       meta: { keepAlive: true }, // keepAlive 为 true 表示当前页面要缓存
   },

修改:scrollBehavior

复制代码
scrollBehavior(to, from, savePosition) {
   if (to.meta.keepAlive && savePosition) {
       // console.log('========>>>savePosition', savePosition);
       return savePosition;
   } else {
       return { x: 0, y: 0 };
   }
},

3. 列表页有选项卡,从首页进来刷新数据,从详情页出来使用缓存数据

https://segmentfault.com/a/1190000014873482

钩子函数的执行顺序

复制代码
#不使用keep-alive
beforeRouteEnter --> created --> mounted --> destroyed

#使用keep-alive
beforeRouteEnter --> created --> mounted --> activated --> deactivated

方法如下:

路由:

复制代码
{
   path: '/articleList',
   name: 'articleList',
   component: resolve => require([/* webpackChunkName: "article" */'@/views/home/article/lists'],resolve),
   meta: { title: '文章列表', keepAlive: true, reload: false },
},

页面:articleList

复制代码
beforeRouteEnter(to, from, next) {
   // 如果不是从详情过来的就刷新缓存
   if (from.path !== '/articleDetails') {
       to.meta.reload = true;
   }
   next();
},
activated() {
   if (this.$route.meta.reload) {
       // 选中index
       this.navIndex = this.$route.query.type;
       // 清理已有列表的数据,重新请求数据,如果不清除的话就会有之前的商品缓存,延迟显示最新的商品
       this.newList = [];
       // 请求数据
       this.getListNewsPage()
   }
   //重新设置当前路由的reload
   this.$route.meta.reload = false;
},

4.千万要注意!!

注意一:在router.js里面一定要看父级的component在那里,我就是把路由入口放在AppMain.vue里面搞了半天才发现不是加在App.vue里面

image.png

注意二:父级元素不要加overflow:auto,不然监听不到滚动,你可以打印savePosition看看

下一篇 / CSS 类似中奖名单的上下滚动特效

🎯 相关文章

💡 推荐文章

🕵️‍♂️ 评论 (0)