Wie kann verhindert werden, dass die Seite nach Routenänderungen in Nuxt scrollt?
P粉865900994
P粉865900994 2023-11-06 18:56:58
0
1
578

Ich habe ein Nuxt-Projekt. Wenn ich von http://localhost:3000/catalog/postery更改路由到http://localhost:3000/catalog/postery/all?photos%5B%5D=262 aus gehe, scrollt meine Seite erst nach oben, nachdem sich meine Route geändert hat

Meine Datei 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 };
}

Wie verhindere ich, dass die Seite nach oben scrollt, bevor ich die Route ändere?

P粉865900994
P粉865900994

Antworte allen(1)
P粉147747637

所以,你确实想要:

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

从Vue路由器的文档来看,你可以使用这样的代码

/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也可能有所帮助。

最后的选择是使用一些过渡效果来隐藏丑陋的抖动/加载,这实际上可以非常吸引人。

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!