gpt4 book ai didi

vue.js - Vue路由器导航或滚动到 anchor (# anchor )

转载 作者:行者123 更新时间:2023-12-05 00:44:55 33 4
gpt4 key购买 nike

我正在为 vue-router 不滚动/导航到 anchor 标签(例如:#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 Router 4 中,从 scrollBehavior() 返回的对象的格式与 Vue Router 3 中的不同。特别是对象的 selector 属性现在命名为 el,如 docs 所示:

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

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

demo

关于vue.js - Vue路由器导航或滚动到 anchor (# anchor ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65204018/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com