gpt4 book ai didi

vue.js - 如何使用路由器链接滚动到特定 anchor ?

转载 作者:行者123 更新时间:2023-12-02 00:18:38 24 4
gpt4 key购买 nike

我正在尝试使用 vue js 开发一个简单的网站,到目前为止一切顺利,但我面临以下问题:

我正在使用路由器更改页面,它可以工作,但我需要做的是:更改页面并滚动到特定 anchor 。

我已经尝试过的:

效果很好:路由到联系页面或主页

<router-link to="/contact">Contact</router-link>
<router-link to="/">Home</router-link>

不起作用:

<router-link :to="{ name: '/', hash: '#technology' }" >Technology</router-link>

最后一个只有在我在主页上时才有效,但每当我切换到联系页面并尝试路由到“/#technology”时,它就不起作用。它确实尝试路由到“http://example.com/contact/#technology”而不是“http://example.com/#technology”。

如果我那样做,它只会滚动到顶部,而不是 anchor :

<router-link to="/#technology" Technology</router-link>

我的路由器代码:

const routes = [
{ path: '/', component: Home },
{ path: '/contact', component: Contact }
]

const router = new VueRouter({
mode: 'history',

routes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;

}

if (to.hash) {
return { selector: to.hash };
}
return { x: 0, y: 0 }
},


});

new Vue({
router,
}).$mount('#app');

模板看起来像这样(我删除了不必要的代码):

<template id="home">
<div>
Home
<div id="technology"> <!-- IT SHOULD SCROLL TO HERE -->
</div>
</template>

<template id="contact">
<div>
Contact Page
</div>
</template>

最佳答案

我认为你走在正确的道路上。

但是您可能误会了 Route namepath 的用法。

代替

<router-link :to="{ name: '/', hash: '#technology' }" >Technology</router-link>

尝试使用 path 而不是 name

<router-link :to="{ path: '/', hash: '#technology' }" >Technology</router-link>

关于vue.js - 如何使用路由器链接滚动到特定 anchor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199247/

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