在使用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中說了
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代碼進行滾動條的頂部返回