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

How to prevent Vuejs scrolling to the top of the page when you press the browser back button

看起来 Vuejs 会在您按下后退按钮时自动滚动到页面顶部,这很奇怪,因为默认情况下 window 在 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
}

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

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

window.history.scrollRestoration = "manual"

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