本文介绍了Vue Router 导航或滚动到锚点(#anchors)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力解决 vue-router 无法滚动/导航到锚点标签(例如:#anchor)的问题.我已经在 Stack Overflow 上阅读了各种解决方案,但到目前为止都没有奏效.

I am struggling with vue-router not scrolling/navigating to anchor tags (ex: #anchor). I have read various solutions here on Stack Overflow, but none have worked so far.

请在下面找到我现在正在使用的代码,但它不起作用:

Please find below the code I am using right now, which is not working:

main.js

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: "/docs/1.0/:title",
            component: Content,
            name: "docs"
        }
    ],
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition;
        }
        if (to.hash) {
            return { selector: to.hash };
        }
        return { x: 0, y: 0 };
    },
});

Content.vue(父组件)

Content.vue (Parent Component)

<template>
  <base-section
    v-for="entry in $store.state.entries"
    :key="entry.title"
    lang="lang-markup"
    :title="entry.title"
  >
    <template v-slot:sectionId>
      <div :id="slugify(entry.title)"></div>
    </template>

    <template v-if="entry.content" v-slot:content>
      <span v-html="entry.content"></span>
    </template>
    <template v-slot:examples>
      <div v-html="entry.examples"></div>
    </template>
    <template v-slot:code>
      {{ entry.code }}
    </template>
  </base-section>
</template>

SectionMenu.vue(子组件)

SectionMenu.vue (Child Component)

<span v-for="item in $store.state.entries" :key="item.title">
  <router-link
    :to="{name:'docs', hash:'#'+slugify(item.title)}"
    class="mx-1 btn btn-primary"
  >{{ item.title }}</router-link>
</span>

我也尝试了不同的方法,但也没有奏效.这是方法:

I have also tried a different approach, but it also hasn't worked. This was the approach:

<button @click.prevent="navigate(item.title)">{{item.title}}</button>
navigate(route){
  this.$router.push({name:'docs', hash:'#'+this.slugify(route)})
},

你知道我做错了什么吗?

Do you have any idea of what I am doing wrong?

PS:我使用的是 VUE 3 (vue CLI 4.5.8)

PS: I am using VUE 3 (vue CLI 4.5.8)

推荐答案

在 Vue Router 4 中,从 scrollBehavior() 返回的对象的格式与它在 Vue Router 3 中的格式有所不同.特别是,对象的 selector 属性现在被命名为 el,如 文档:

In Vue Router 4, the format of the returned object from scrollBehavior() has changed from what it was in Vue Router 3. In particular, the object's selector property is now named el, as shown in the docs:

const router = createRouter({
  scrollBehavior(to, from, savedPosition) {
    if (to.hash) {
      // BEFORE:
      // return { selector: to.hash }

      return { el: to.hash }
    }
  },
})

演示

这篇关于Vue Router 导航或滚动到锚点(#anchors)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 15:09