遇到的问题:在首页列表展示点击跳转到详情页面时,发现详情页并没有展示到页面顶部位置
原因:Vue Router 默认的是在每次导航后不会滚动页面到顶部。但是可以通过在路由配置中加入scrollBehavior方法来自定义滚动行为
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
// ...路由配置
],
scrollBehavior (to, from, next) {
return { top: 0 }
}
})
export default router
但上述代码好像并不包含初始页的加载,如果初始页也需要在加载时展示到顶部位置,可能需要再main.ts文件中使用window.scrollTo(0, 0)