img

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

2021-01-06 0条评论 3.1k次阅读 JavaScript


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

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看看

💬 COMMENT


🦄 支持markdown语法

👋友