[Nuxt.js]在iOS上备份浏览器时,它不会返回到原始滚动位置


(请告诉我是否有更好的方法!!?)

概述

在Nuxt.js项目中,当我过渡到外部页面并返回浏览器时,
它已返回到屏幕顶部,因此请采取措施。

结论

app/router.scrollBehavior.js添加到您的主目录并实现以下代码

应用程序/ router.scrollBehavior.js

1
2
3
4
5
6
7
if (process.client) {
  if ('scrollRestoration' in window.history) {
    window.addEventListener('load', () => {
      window.history.scrollRestoration = 'auto'
    })
  }
}

原因

滚动位置恢复设置在现有的router.scrollBehavior.js中实现,但是
在iOS上不会触发Beforeunload。
因此window.history.scrollRestoration未设置为auto,
由于window.history.scrollRestoration设置为manual,因此在备份浏览器时,它将返回到屏幕顶部。

作为对策,实施以确保始终设置window.history.scrollRestoration = auto

node_modules / @ nuxt / vue-app /模板/router.scrollBehavior.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 7行目?23行目
if (process.client) {
  if ('scrollRestoration' in window.history) {
    window.history.scrollRestoration = 'manual'

    // reset scrollRestoration to auto when leaving page, allowing page reload
    // and back-navigation from other pages to use the browser to restore the
    // scrolling position.
    window.addEventListener('beforeunload', () => {
      window.history.scrollRestoration = 'auto'
    })

    // Setting scrollRestoration to manual again when returning to this page.
    window.addEventListener('load', () => {
      window.history.scrollRestoration = 'manual'
    })
  }
}

参考

?恢复搜寻位置
?beforeunload在iOS上不起作用
?scrollBehavior