vant list組件滾動保留滾動條位置,結合keepAlive


前提是用的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>

 

首先在路由文件router.js,給每個路由meta添加scrollTop和keepAlive

{
      path: '/',
      name: 'home',
      meta: {
        title: "標題",
        keepAlive: true,
        scrollTop: 0
      },
      component: Home
 },

然后在main.js,記錄滾動條的位置

router.beforeEach((to, from, next) => {  
  if (from.meta.keepAlive) {
    const $content = document.querySelector('.content'); // 列表的外層容器
    const scrollTop = $content ? $content.scrollTop : 0;
    console.log('scrollTop', scrollTop)
    from.meta.scrollTop = scrollTop;
  }
  next();
});

最后在需要記錄保留滾動條位置的地方獲取通過activated(這個函數每次進入頁面都會執行,只有結合使用keepAlive組件才有效)來獲取scrollTop,

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM