最近項目中遇到這樣一個問題,vue切換路由,頁面到頂端的滾動距離仍會保持不變。
方法一: 監聽路由
// app.vue
export default { watch:{ '$route':function(to,from){
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
} }
方法二: 全局路由衛士
// router.js router.afterEach(() => { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; })
補充: hash模式下才會導致上述問題,history模式下vue官網有更好的處理方法。