背景
路由跳轉時進入新的頁面,但位置卻不在頂部,而是在上個頁面瀏覽的位置,在每次進入新頁面時,想讓它定位在頁面的頂部。
代碼
方式一
main.js
router.beforeEach((to, from, next) => {
// chrome
document.body.scrollTop = 0
// firefox
document.documentElement.scrollTop = 0
// safari
window.pageYOffset = 0
next()
})
每次點擊分頁的時候,頁面也會停留在之前瀏覽的位置,在調完接口后也加入下面幾行代碼就好了。
// chrome
document.body.scrollTop = 0
// firefox
document.documentElement.scrollTop = 0
// safari
window.pageYOffset = 0
方式二
router-index.js
const router = new VueRouter({
routes: [...],
scrollBehavior (to, from, savedPosition) {
// return 期望滾動到哪個的位置
return { x: 0, y: 0 }
}
})