vue2.0路由切换后页面滚动位置不变BUG

最近项目中遇到这样一个问题,vue切换路由,页面到顶端的滚动距离仍会保持不变。

 方法一: 监听路由

// app.vue    
export default {
        watch:{
            '$route':function(to,from){
           document.body.scrollTop = 0;
                 document.documentElement.scrollTop = 0; 
           }
        }
    }

方法二: 全局路由卫士

// router.js
router.afterEach(() => {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
})

补充: hash模式下才会导致上述问题,history模式下vue官网有更好的处理方法。

猜你喜欢

转载自blog.csdn.net/ddwddw4/article/details/82225940