Vue路由器导航或滚动到锚点(#anchors)



我正在为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路由器4中,scrollBehavior()返回的对象的格式与Vue路由器3中的格式不同。特别是,对象的selector属性现在命名为el,如文档所示:

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

演示

最新更新