如何在Nuxt中實現路由更改後頁面不滾動?
P粉865900994
P粉865900994 2023-11-06 18:56:58
0
1
425

我有一個Nuxt專案。當我從http://localhost:3000/catalog/postery更改路由到http://localhost:3000/catalog/postery/all?photos[]=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 };
}

我如何在更改路由之前防止頁面滾動到頂部?

P粉865900994
P粉865900994

全部回覆(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也可能有幫助。

最後的選擇是使用一些過渡效果來隱藏醜陋的抖動/加載,這實際上可以非常吸引人。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!