如何防止按下浏览器后退按钮时 Vuejs 滚动到页面顶部

MrR*_*Red 3 vue.js vue-router

当您按下后退按钮时,Vuejs 看起来会自动滚动到页面顶部,这很奇怪,因为默认情况下,当您在 SPA 中更改路由或转到新页面时,窗口甚至不会滚动到顶部。您需要显式设置scrollBehaviour以滚动到顶部。那么如何才能防止按下后退按钮时页面自动滚动到顶部呢?

beforeRouteLeave (to, from, next) {
    alert('Are you sure you want to leave this page and lose unsaved changes')
    // Notice how the page automatically scrolls to the top here even if the user were to response 'No' in a dialog situation
}
Run Code Online (Sandbox Code Playgroud)

这是问题的代码笔 https://codepen.io/anon/pen/bOGqVP

Eri*_*ino 5

浏览器后退按钮滚动到顶部由浏览器定义。显然我们可以通过添加这行代码来禁用该行为

window.history.scrollRestoration = "manual"
Run Code Online (Sandbox Code Playgroud)

添加此代码将告诉浏览器我们处理滚动。我只在你的代码笔中测试这个。需要在其他浏览器中测试