需求描述
希望在两种情况下实现不同的滚动行为:
- 当用户通过点击链接跳转到新页面时,希望页面滚动到顶部
- 当用户使用浏览器的返回按钮时,希望页面恢复到之前的滚动位置
Vue Router 的
函数可以帮助我们解决这个问题,它可以根据导航类型来决定滚动行为。const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), scrollBehavior(to, from, savedPosition) { // 如果有保存的位置(使用浏览器的前进/后退按钮时) if (savedPosition) { return savedPosition; } // 否则滚动到顶部 return { left: 0, top: 0 }; }, routes: [ { path: '/', name: 'home', component: HomeView }, { path: '/search', name: 'search', component: () => import('../views/search/Search.vue'), meta: { keepAlive: true } }, { path: '/:catchAll(.*)', component: () => import('../views/system/NotFound.vue') } ] })
文章评论