2

I have Nuxt project. When I change the route from http://localhost:3000/catalog/postery to http://localhost:3000/catalog/postery/all?photos%5B%5D=262 my page is scrolled up to the top, and only after my route is changing

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 I can prevent scroll up before changing route?

kissu
  • 40,416
  • 14
  • 65
  • 133
KAVA
  • 197
  • 1
  • 4
  • 16
  • So, if you don't want to scroll up, what do you want? Stay at the same level of scrolling on th next page? What is the purpose and what are you targeting with this behavior? – kissu Aug 17 '21 at 09:32
  • @kissu i want that my current page dont scroll up before my route is changing. I want save position that i have before going to new route – KAVA Aug 17 '21 at 11:35

1 Answers1

2

So, you do want to:

  • click on a link
  • start to render the page
  • scroll to top

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

/app/router.scrollBehavior.js

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

You could maybe also make it conditional or with a setTimeout like this

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 answer using vue-scrollto can also maybe help.

Last resort would be to use some transitions to hide the ugly jitter/loading, this can actually be pretty sexy.

kissu
  • 40,416
  • 14
  • 65
  • 133