Home  >  Q&A  >  body text

How to prevent the page from scrolling after route changes in Nuxt?

I have a Nuxt project. When I change the route from http://localhost:3000/catalog/postery to http://localhost:3000/catalog/postery/all?photos[]=262, My page scrolls to the top only after my route changes

My file scrollBehavior.js:

export default async function (to, from, savedPosition) {
  
  if (
    (to.path.indexOf("/catalog/") !== -1 &&
      to.path.indexOf("/all") === -1 &&
      Object.keys(to.query).length > 0) || 
    (to.path.indexOf("/search") !== -1 && Object.keys(to.query).length > 0) || 
    (to.name === "product-type-id" && Object.keys(to.query).length > 0) || 
    (from.name === "product-type-id" &&
      to.name === "product-type-id" &&
      to.params.type != from.params.type) 
  ) {
    return;
  }

  if (to.path.indexOf("/catalog/") !== -1 && savedPosition != null) {
    return { x: 0, y: savedPosition.y };
  }

  return { x: 0, y: 0 };
}

How do I prevent the page from scrolling to the top before changing the route?

P粉865900994P粉865900994347 days ago657

reply all(1)I'll reply

  • P粉147747637

    P粉1477476372023-11-07 14:51:34

    So, you do want:

    • click the link
    • Start rendering page
    • Scroll to top

    From the documentation of Vue router, you can use code like this

    /app/router.scrollBehavior.js

    export default function () {
      return { x: 0, y: 0, behavior: 'smooth' }
    }
    

    You can also use conditions or setTimeout to achieve

    export default function (to, from, savedPosition) {
      if (to.path === '/my-cool-path') {
        return { x: 0, y: 0, behavior: 'smooth' }
      }
    }
    
    export default function (to, from, savedPosition) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve({ x: 0, y: 0, behavior: 'smooth' })
        }, 2000)
      })
    }
    

    This answerusing vue-scrollto may also help.

    The final option is to use some transition effects to hide the ugly shaking/loading, which can actually be very attractive.

    reply
    0
  • Cancelreply