vue-router scrollBehavior無效的問題及解決方案


 在使用vue做單頁面應用開發時候 使用vue-router作為路由控制器  在使用過程中發現每個頁面打開都在原來的位置 不能返回到頁面頂部位置 ,然后查看api文檔

  滾動行為  發現如下代碼:

const router = new VueRouter({
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
    // return 期望滾動到哪個的位置
    scrollBehavior (to, from, savedPosition) {
      if (savedPosition) {
           return savedPosition
      } else {
      return { x: 0, y: 0 }
   }
 }
  }
})

添加路由中后發現沒有實際效果。。。

再細查資料發現作者在[issues](https://github.com/vuejs/vue-router/issues/675)中說了  

Hooking into transitions involves too many intricacies and depends on custom transition implementations, so vue-router is not going to support that as a built-in. It's possible to implement your own transition component for that purpose though.

意思是vue-router不在支持這個特性了

 

解決方式:  

router.beforeEach((to, from, next) => {
document.body.scrollTop = 0;
next()
});

 在路由遍歷中使用js代碼進行滾動條的頂部返回

以上內容來源: http://www.cnblogs.com/DemoLee/p/6964959.html

 

然而, 實際操作中,發現document.body.scrollTop 一直未0, 

查詢資料. 傳送門: [documentbodyscrollTop的值總為零的解決辦法](https://www.cnblogs.com/starof/p/5238654.html)

 

解決辦法如下:

router.afterEach((to, from) => {
  let bodySrcollTop = document.body.scrollTop
  if (bodySrcollTop !== 0) {
    document.body.scrollTop = 0
    return
  }
  let docSrcollTop = document.documentElement.scrollTop
  if (docSrcollTop !== 0) {
    document.documentElement.scrollTop = 0
  }
})

 

參考鏈接:

1. [Vue 2 router scrollBehavior not working for layout views](https://github.com/quasarframework/quasar/issues/161) 該issue中提到可使用[vue-scroll-behavior](https://www.npmjs.com/package/vue-scroll-behavior)(https://www.npmjs.com/package/vue-scroll-behavior) 

2. [vue-router](https://github.com/vuejs/vue-router/issues/675) 


免責聲明!

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



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