Explorar el Código

链接跳转时默认会保留上一个页面的滚动位置, 或者因为 SPA 的特性, 浏览器认为还在当前窗口, 所以没有自动回到顶部, 在 router/index.js 中使用 scrollBehavior 函数, 每次路由切换时,Vue 会自动帮你滚动到顶部

reghao hace 1 día
padre
commit
81e42de0c2
Se han modificado 1 ficheros con 7 adiciones y 1 borrados
  1. 7 1
      src/router/index.js

+ 7 - 1
src/router/index.js

@@ -183,6 +183,12 @@ export default new VueRouter({
   mode: 'history',
   routes: constantRoutes,
   scrollBehavior(to, from, savedPosition) {
-    return { x: 0, y: 0 }
+    if (savedPosition) {
+      // 如果是通过浏览器后退按钮,则回到之前的滚动位置
+      return savedPosition
+    } else {
+      // 否则每次跳转都滚动到顶部
+      return { x: 0, y: 0 }
+    }
   }
 })