滚动行为
使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。 vue-router
能做到,而且更好,它让你可以自定义路由切换时页面如何滚动。
注意: 这个功能只在支持 history.pushState
的浏览器中可用。
const router = createRouter({
history: createWebHashHistory(),
routes: [...],
scrollBehavior (to, from, savedPosition) {
// return 期望滚动到哪个的位置
// 始终滚动到顶部
return { top: 0 }
}
})
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
参数
to
from
savedPosition
:第三个参数savedPosition
,只有当这是一个popstate
导航时才可用(由浏览器的后退/前进按钮触发)。
scrollBehavior
返回滚动位置的对象信息
const router = createRouter({
history: createWebHistory(),
scrollBehavior: (to, from, savePosition) => {
return {
top:200
}
},
1
2
3
4
5
6
7
2
3
4
5
6
7
如果有savePosition
,则赋值
const router = createRouter({
history: createWebHistory(),
scrollBehavior: (to, from, savePosition) => {
if(savePosition){
return savePosition
} else {
top: 0
}
},
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 延迟滚动
有时候,我们需要在页面中滚动之前稍作等待。
例如,当处理过渡时,我们希望等待过渡结束后再滚动。要做到这一点,你可以返回一个 Promise,它可以返回所需的位置描述符。
const router = createRouter({
history: createWebHistory(),
scrollBehavior: (to, from, savePosition) => {
console.log(to, '==============>', savePosition);
return new Promise((r) => {
// 2秒钟之后top为10000
setTimeout(() => {
r({
top: 10000
})
}, 2000);
})
},
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
上次更新: 2024/08/14, 04:14:33