温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vant中list组件滚动保留滚动条位置的示例分析

发布时间:2021-09-13 13:03:15 来源:亿速云 阅读:819 作者:小新 栏目:开发技术

这篇文章主要介绍vant中list组件滚动保留滚动条位置的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

vant list组件滚动保留滚动条位置,需结合keepAlive使用。

1、保存位置的前提是用的keepAlive组件来做缓存,app.vue代码

<template>
  <div id="app">
    <keep-alive>
      <router-view v-if='$route.meta.keepAlive'/>
    </keep-alive>
    <router-view  v-if='!$route.meta.keepAlive'/>
  </div>
</template>

2、在路由文件router.js,给每个路由meta添加scrollTop和keepAlive

 {
      path: '/home',
      name: 'home',
      component: resolve => require(['@/views/home/index.vue'], resolve),
      meta: {
        title: '首页',
        index: 1,
        keepAlive: true,
        scrollTop: 0
      }
    },
    {
      path: '/classify',
      name: 'classify',
      component: resolve => require(['@/views/classify/index.vue'], resolve),
      meta: {
        title: '分类',
        index: 1,
        keepAlive: true,
        scrollTop: 0
      }
    },
    {
      path: '/shopping',
      name: 'shopping',
      component: resolve => require(['@/views/shopping/index.vue'], resolve),
      meta: {
        title: '购物车',
        index: 1,
        keepAlive: true,
        scrollTop: 0
      }
    },
    {
      path: '/detail',
      name: 'detail',
      component: resolve => require(['@/views/detail/index.vue'], resolve),
      meta: {
        title: '详情',
        index: 2,
        // keepAlive: true,
        // scrollTop: 0
      }
    },

3、然后在main.js,记录滚动条的位置

router.beforeEach((to, from, next) => {  
  if (from.meta.keepAlive) {
    const $wrapper = document.querySelector('.app-wrapper'); // 列表的外层容器 注意找到滚动的盒子
    const scrollTop = $wrapper ? $wrapper.scrollTop : 0;
    console.log('scrollTop=', scrollTop)
    from.meta.scrollTop = scrollTop;
  }
  next();
});

vant中list组件滚动保留滚动条位置的示例分析

4、最后在需要记录保留滚动条位置的地方获取通过activated(这个函数每次进入页面都会执行,只有结合使用keepAlive组件才有效)来获取scrollTop

activated () {
    const scrollTop = this.$route.meta.scrollTop;
    const $wrapper = document.querySelector('.app-wrapper');
    if (scrollTop && $wrapper) {
      $wrapper.scrollTop = scrollTop;
    }
  },

比如缓存了某些页面也不想随之滚动,则把scrollTop置0即可;

activated() {
    const $wrapper = document.querySelector(".app-wrapper");
    $wrapper.scrollTop = 0;
  },

注意,页面滚动的话,其他页面有滚动条的也会随之滚动,可以对其他页面里面处理,或者判断是否从详情页到列表页来判断是否缓存位置,如果不是,则回到顶部,但是注意路由钩子函数this的使用;

以上是“vant中list组件滚动保留滚动条位置的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI