Vue.js动态路由间切换回到顶部

AI摘要:Vue.js动态路由切换回到顶部有两种方案:1.使用滚动行为功能(需开启HTML5 history模式);2.使用导航守卫router.beforeEach,通过window.scrollTo(0,0)实现页面回到顶部。

方案1

使用官方的滚动行为,但是必须开启HTML5 history 模式,开启HTML5 history 模式需要后端进行一些配置;

对于所有路由导航,简单地让页面滚动到顶部:

scrollBehavior (to, from, savedPosition) {
  return { x: 0, y: 0 }
}

像浏览器的原生表现那样:

scrollBehavior (to, from, savedPosition) {
  if (savedPosition) {
    return savedPosition
  } else {
    return { x: 0, y: 0 }
  }
}

方案2

没有使用HTML5 history 模式,需要使用官方的导航守卫中的router.beforeEach

router.beforeEach((to, from, next) => {
  window.scrollTo(0, 0)  
  next()
});

添加新评论