vue 返回滾動位置


 

list頁面要使用keep-alive,這里再app.vue里判斷

app.vue

    <keep-alive>
      <router-view v-if="$route.meta.keepAlive"></router-view>
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive"></router-view>

 

router.js

使用history模式 scrollBehavior里是具體代碼,一開始是在scrollBehavior里獲取

 document.documentElement.scrollTop || document.body.scrollTop;但是第一次進入頁面的時候滾動頁面高度無法獲取,所以就在list.vue里
beforeRouteLeave方法里設置高度,然后就可以在scrollBehavior return相應的高度了

export default new Router({
  mode: "history",
  base: "/m/",
  scrollBehavior(to, from, savedPosition) {
  return { x: 0, y: to.meta.savedPosition || 0 };
},
routes: [
  {
    path: "/",
    name: "list",
    component: List,
    meta: { keepAlive: true }
  } 
]
});

 

list.vue

    beforeRouteLeave(to, from, next) {
      let position = document.documentElement.scrollTop || document.body.scrollTop;
      from.meta.savedPosition = position;
      next()
    },

 


免責聲明!

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



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