Vue Router 导航或滚动到锚点(#anchors)

Sla*_*orx 5 vue.js vue-router vuejs3

我正在努力vue-router不滚动/导航到锚标记(例如#anchor:)。我在 Stack Overflow 上阅读了各种解决方案,但到目前为止还没有一个有效。

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

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 };
    },
});
Run Code Online (Sandbox Code Playgroud)

Content.vue(父组件)

<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>
Run Code Online (Sandbox Code Playgroud)

SectionMenu.vue(子组件)

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

你知道我做错了什么吗?

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

ton*_*y19 9

在 Vue Router 4 中,返回对象的格式与 Vue Router 3 中的格式scrollBehavior()发生了变化。特别是,对象的selector属性现在被命名为el,如文档中所示:

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

      return { el: to.hash }
    }
  },
})
Run Code Online (Sandbox Code Playgroud)

演示