1.导航守卫
Vue.use(VueRouter);
const router = new VueRouter({ routes }) router.beforeEach((to, from, next) => { // 让页面回到顶部 document.documentElement.scrollTop = 0 // 调用 next(),一定要调用 next 方法,否则钩子就不会被销毁 next() })
或
this.$router.beforeEach((to, from, next) => { //to 即将要进入的目标 //from 当前导航正要离开的路由 //next 必须调用next才可以进行页面跳转 })
- to:Route: 即将要进入的目标路由对象
- from: Route: 当前导航正要离开的路由
- next: Function: 调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数,所以一定要调用next方法
2 Vur Router提供的scrollBehavior 方法-简单的让页面滚动到顶部(?)
// 每次做路由切换时,始终回到最顶部 scrollBehavior (to, from, savedPosition) { return { x: 0, y: 0 } }