2024年3月24日发(作者:)
vue项目中,滚动条恢复初始位置的方法
一、使用Vue-router滚动行为:
你可以使用Vue-router的滚动行为,让每个路由的滚动条恢复
到初始位置。
1、在 router/中添加以下代码:
const router = new VueRouter({
mode: 'history',
scrollBehavior (to, from, savedPosition) {
return { x: 0, y: 0 }
},
routes
})
/*
mode: 'history', 将路由设置为HTML5 History 模式
scrollBehavior (to, from, savedPosition)定义滚动行为,返
回需要滚动到的位置对象
{ x: 0, y: 0 }表示滚动到顶部,如果想滚动到指定的位置,你
可以返回{ x: 0, y: 100 },这是表示滚动到 100 像素高度
*/
2、引入组件,在组件中定义 mounted 事件:
mounted() {
this.$nextTick(() => {
- 1 -
To(0, 0);
});
}
/*
this.$nextTick表示当组件被挂载完成之后,才会触发函数,
To用来将滚动条恢复到初始位置,设置 x 为 0,y 为
0 则表示滚动条恢复到顶部,其他位置同理。
*/
二、使用 JavaScript 的 scrollTo 方法:
使用 JavaScript 的 scrollTo 方法,可以在切换到某个页面的
时候让滚动条恢复到初始位置。
1、在 router/ 中添加以下代码:
routes: [
{
path: '/',
component: Home,
beforeEnter: (to, from, next) => {
To(0, 0);
next();
}
}
]
- 2 -
/*
在 beforeEnter 中调用 To 方法将滚动条恢复
到初始位置,当 beforeEnter 函数执行完毕之后才会跳转到目标路
由
*/
2、在组件中定义 mounted 事件:
mounted() {
this.$nextTick(() => {
To(0, 0);
});
}
/*
this.$nextTick表示当组件被挂载完成之后,才会触发函数,
To用来将滚动条恢复到初始位置,设置 x 为 0,y 为
0 则表示滚动条恢复到顶部,其他位置同理。
- 3 -
发布评论