【问题标题】:Hash anchor reloads the page when first clicked哈希锚在第一次点击时重新加载页面
【发布时间】:2022-11-10 22:02:10
【问题描述】:

当我单击带有类似 href='#title' 的 href 的锚点时,我希望页面滚动到包含 id='title' 的元素。`

相反,它会重新加载页面,如果我第二次单击它,它就会起作用。我正在使用 vue-router,这是router.options

import type { RouterOptions } from '@nuxt/schema'

export default <RouterOptions>{
  strict: true,
  scrollBehavior: function (to, _from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else if (to.hash) {
      return {
        el: to.hash,
      }
    } else {
      return {
        left: 0,
        top: 0,
      }
    }
  },
}

【问题讨论】:

标签: typescript vue.js nuxt.js vue-router


【解决方案1】:

嘿,几周前我遇到了同样的问题。 这是我的解决方案:

import type { RouterConfig } from '@nuxt/schema'

// https://router.vuejs.org/api/#routeroptions
export default <RouterConfig>{
  scrollBehavior(to, from, savedPosition) {
    const nuxtApp = useNuxtApp()

    // If history back
    if (savedPosition) {
      // Handle Suspense resolution
      return new Promise((resolve) => {
        nuxtApp.hooks.hookOnce('page:finish', () => {
          setTimeout(() => resolve(savedPosition), 50)
        })
      })
    }
    // Scroll to heading on click
    if (to.hash) {
      setTimeout(() => {
        const heading = document.querySelector(to.hash) as any

        return window.scrollTo({
          top: heading.offsetTop,
          behavior: 'auto',
        })
      })
      return
    }

    // route change
    if (from.path !== to.path) {
      nuxtApp.hooks.hookOnce('page:finish', () => {
        window.scrollTo({
          top: 0,
          behavior: 'smooth',
        })
        return
      })
    }

    return { top: 0 }
  },
}

【讨论】:

    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多