問題
Vue路由跳轉(zhuǎn),目標(biāo)頁面會(huì)繼承起始頁面的滾動(dòng)條的位置。
history.scrollRestoration
有這樣一個(gè) API 可以修改瀏覽器的滾動(dòng)恢復(fù)行為,它有兩個(gè)值:
auto
將恢復(fù)用戶已滾動(dòng)到的頁面上的位置。
manual
未還原頁上的位置。用戶必須手動(dòng)滾動(dòng)到該位置。
使用
const scrollRestoration = history.scrollRestoration
if (scrollRestoration === 'manual') {
console.log('未還原頁面上的位置,用戶將需要手動(dòng)滾動(dòng)');
}
scrollRestoration = 'auto' // 恢復(fù)頁面滾動(dòng)恢復(fù)行為
兼容性如下

image.png
window.scrollTo
實(shí)際使用發(fā)現(xiàn) history.scrollRestoration 在 Vue 路由跳轉(zhuǎn)上使用并不好使
只好在目標(biāo)頁面增加window.scrollTo(0, 0)手動(dòng)將頁面滾動(dòng)的頂部。