首页 > 解决方案 > Vue路由器导航或滚动到锚点(#锚点)

问题描述

我正在努力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 };
    },
});

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>

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>

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

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

你知道我做错了什么吗?

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

标签: vue.jsvue-routervuejs3

解决方案


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

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

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

演示


推荐阅读