官方文档:
https://router.vuejs.org/zh/guide/advanced/scroll-behavior.html#%E5%BC%82%E6%AD%A5%E6%BB%9A%E5%8A%A8
使用前端路由,当切换到新路由时,想要页面滚到顶部,或者是保持原先的滚动位置,就像重新加载页面那样。 vue-router
能做到,而且更好,它让你可以自定义路由切换时页面如何滚动。
实际例子:通过vue-router提供的scrollBehavior函数来控制滚动的位置的不由切换页面而改变
1 //创建路由 2 export const createRouter = () => new VueRouter({ 3 // https://router.vuejs.org/zh/guide/advanced/scroll-behavior.html#%E5%BC%82%E6%AD%A5%E6%BB%9A%E5%8A%A8 4 // 这个方法 是控制滚动条 5 // 如果 retuen falsy || {} ,则不发生滚动 6 scrollBehavior (to, from, savedPosition) { 7 // savedPosition 这个参数当且仅当导航 (通过浏览器的 前进/后退 按钮触发) 时才可用 效果和 router.go() 或 router.back() 8 if (savedPosition) { 9 // 返回savedPosition 其实就是 当用户点击 返回的话,保持之前游览的高度 10 return savedPosition 11 } else { 12 if (from.meta.keepAlive) { 13 from.meta.savedPosition = document.body.scrollTop 14 } 15 return { 16 x: 0, 17 y: to.meta.savedPosition || 0 18 } 19 } 20 }, 21 mode: 'history', 22 routes: [...PageRouter, ...ViewsRouter] 23 })