nuxt: import router from '~router' stopped working

Hello. I had a fix for scrolling to top behavior when page transition, but with latest Nuxt releases it stoped working. It was a plugin:

import router from '~router'

router.afterEach((to, from) => {
  setTimeout(() => {
    if (document) document.body.scrollTop = 0
  }, 515)
})

But now this import router from '~router' gives me an error.

Any tips how to fix it? How to access router with latest API?

<div align="right">This question is available on Nuxt.js community (#c1489)</div>

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 51

Most upvoted comments

ok i found it. you need to disable the default scroll behavoir in nuxt config

  router: {
    scrollBehavior: function (to, from, savedPosition) {
      if (savedPosition) return savedPosition
      return false
    }
  },

your website isnt working in chrome canary. I think it was with window.document.body.scrollTop = 0 right?

you are welcome.

With page ransition

scroll.js

export default ({ app }) => {
  app.router.afterEach(function (to, from, next) {
    setTimeout(() =>{
      window.scrollTo(0, 0)
    },115)
  })
}

nuxt.conf.js (a little different)

  router: {
    scrollBehavior (to, from, savedPosition) {
      if (savedPosition) return savedPosition
      return false
    }
  }

_animation.scss

.page-enter-active, .page-leave-active {
  transition: opacity .1s;
}
.page-enter, .page-leave-to {
  opacity: 0;
}

@homerjam can you please give a link to that PR that I can know what is happening?