在 Nuxt 中更改路由后如何不向下滚动页面?

How not to scroll down a page after a route change in Nuxt?

我有 Nuxt 项目。当我将路线从 http://localhost:3000/catalog/postery 更改为 http://localhost:3000/catalog/postery/all?photos%5B%5D=262 时,我的页面向上滚动到顶部,并且仅在我的路线发生变化后

我的文件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 };
}

如何防止在更改路线之前向上滚动?

那么,您确实想要:

  • 点击 link
  • 开始渲染页面
  • 滚动到顶部

从 Vue 路由器 documentation 看来,您可以使用这种代码

/app/router.scrollBehavior.js

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

你也可以让它成为有条件的或者像这样setTimeout

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)
  })
}

使用 vue-scrollto 也可能有所帮助。

最后的办法就是用一些 transitions 来掩饰丑陋 jitter/loading,这实际上可以很性感。