【问题标题】:How can I scroll to the heading that is added to the url after `#`?如何滚动到“#”之后添加到 url 的标题?
【发布时间】:2020-05-17 02:48:57
【问题描述】:

我正在使用 Nuxtjs(Vue),并且我有一个带有标题的侧边栏,并且正在滚动监视包含这些标题的主要内容。我正在使用来自 Boostrap Vue(https://bootstrap-vue.js.org/docs/directives/scrollspy/#example-using-list-group) 的 Scrollspy。每次单击其中一个标题时,都会使用标题名称更新 url(这很好用)。我正在将所有标题转换为

  1. 小写
  2. 删除所有特殊字符
  3. 将所有空格转换为连字符

然后将它们添加到#之后的URL

示例:现在当有人输入 https://www.mydomainname.com/myarticlelisting/myarticlename#heading-3 时,我希望它滚动到标题 3 所在的位置。

工作原理:点击侧边栏的标题会更新网址并滚动到标题。

什么不起作用:当在# 之后输入带有标题名称的 URL 时,它不会滚动到相应的标题。

这就是我所拥有的:

我的侧边栏:

          <div v-b-scrollspy>
            <div class="sidebar_headings">
              <b-list-group
                v-for="(item, indexheading) in article.mainContent[
                  'en'
                ].filter(item => item.component === 'heading')"
                :key="indexheading"
              >
                <b-list-group-item
                  v-if="item.component === 'heading'"
                  :to="`#${handleheading(item.text)}`"    <--- The reference to the headings
                >
                  {{ item.text }}
                </b-list-group-item>
              </b-list-group>
            </div>
          </div>

我的主要内容:

          <div
            v-for="(item, index) in article.mainContent['en']"
            :key="index"
          >

            <header-component
              :id="handleheading(item.text)"          <-- The headings
              v-html="
                `<${item.tag}>${item.text}</${item.tag}>`
              "
             />
         </div>

我的方法:

handleheading(heading: any): any {
    const convertSpacesToDashesAndLowercase = heading
      .replace(/\s+/g, '-')
      .toLowerCase();
    const removeSpecialCharacters = convertSpacesToDashesAndLowercase.replace(
      /[^A-Za-z-]/g,
      ''
    );
    return removeSpecialCharacters;
  }

Jquery,不是一个选项 :) 我将不胜感激。谢谢!

【问题讨论】:

  • 你检查过开发控制台吗?您是否使用通用应用程序 (SSR)?我可以想象 Nuxt 在 url 中找不到锚点。

标签: javascript vue.js vuejs2 nuxt.js scrollspy


【解决方案1】:
mounted() {
  const el = document.querySelector(this.$route.hash)
  el && el.scrollIntoView()
}

这就解决了!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多