由于单页面应用的原理,使用vue搭建的项目在路由切换时并不会刷新整个页面。因此在有滚动条的页面会存在滚动条不能自动重置的问题。在最近的项目中就遇到了这种问题,因此记录一下。
1.切换路由:
<el-main>
<!--<router-view />-->
<router-view v-slot="{ Component }">
<transition name="fade-slide" mode="out-in" appear>
<component :is="Component" id="main" />
</transition>
</router-view>
</el-main>
onBeforeRouteUpdate((to, from) => {
// 由于路由设置了0.3s过渡效果,所以此处设置了0.3s定时器。避免页面切换效果突兀。
setTimeout(() => {
document.getElementById("main").scrollIntoView({
behavior: "smooth",
block: "start",
});
}, 300);
})
2.el-table
<el-table ref="tableRef"></el-table>
onUpdated(() => {
console.log(tableRef.value)
if(tableRef.value != null) {
tableRef.value.setScrollTop(0)
tableRef.value.setScrollLeft(0)
}
})
本文讲述了在使用Vue开发的单页面应用中,如何处理路由切换时滚动条不自动重置的问题,通过`onBeforeRouteUpdate`设置定时器和`el-table`组件的`onUpdated`方法来实现滚动条的平滑重置。


8891

被折叠的 条评论
为什么被折叠?



