Nuxt.js 页面跳转后不会滚动至顶部,以及路由守卫应用

在做项目的过程中,遇到页面切换后不会滚动到顶部
解决方案:
在页面使用的layout中或者页面中,使用监听

watch: {
    '$route': function(to,from){
			 document.body.scrollTop = 0
      		 document.documentElement.scrollTop = 0
     		 this.$refs.scroll.scrollTop = 0   // 因为我的的滚动层不是body,所以将滚动层的scrollTop 至为0
    }
  },

还有在官方文档中看到的其他解决方案,大家可以试下

  1. nuxt.config.js:中配置
module.exports = {
  router: {
    scrollBehavior (to, from, savedPosition) {
      return { x: 0, y: 0 }
    }
  }
}
  1. 默认情况下,从当前页面切换至目标页面时,Nuxt.js 会让目标页面滚动至顶部。但是在嵌套子路由的场景下,Nuxt.js 会保持当前页面的滚动位置,除非在子路由的页面组件中将 scrollToTop 设置为 true。
<template>
  <h1>子页面组件</h1>
</template>

<script>
export default {
  scrollToTop: true
}
</script>
  1. 我们可以在nuxt.config.js:配置所有页面渲染后滚动至顶部:
module.exports = {
  router: {
    scrollBehavior (to, from, savedPosition) {
      return { x: 0, y: 0 }
    }
  }
}
  1. 使用路由守卫,在nuxt中配置路由守卫可以在plugins文件下新建router.js在里面写入
export default ({  app }) => {

app.router.afterEach((to, from, next) => {
   document.body.scrollTop = 0
   document.documentElement.scrollTop = 0
   // 或者滚动容器的scrollTop = 0
});
/*----------------------------下面是给页面加入百度统计代码的方法,有需要的可以参考下-----------------------------------------*/
  app.router.beforeEach((to, from, next) => {
    next();
    if (process.client) {
      let _hmt = _hmt || [];
      // 百度统计代码
      (function() {
        let hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?0cb92588b9c690b3c48173df77fa700d";
        let s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    }
  })
}

然后在nuxt.config.js中配置
module.exports = {
 plugins: [
    {src: '@/plugins/router', ssr: false}
  ],
}

然后  重启项目

具体的可以看官方文档https://zh.nuxtjs.org/api/configuration-router https://zh.nuxtjs.org/api/pages-scrolltotop