如何使用 Vue Router 创建锚标签 [英] How to create anchor tags with Vue Router
问题描述
我正在创建一个小的 Vue 网络应用程序,我想在其中创建一个锚标记.
我已经给其中一个 div
提供了一个 id
我想要这样的锚标签:
....
这是我的路由器配置:
导出默认的新路由器({摘要:真实,模式:'历史',滚动行为:() =>({ y: 0 }),路线: [{ 路径:'/',组件:abcView}]})
但是这个锚标签有时有效,有时无效,我错过了什么吗?
我相信您是在询问直接跳转到页面的特定区域,方法是导航到页面内的 #section-3
等锚标记.
为此,您需要按如下方式修改 scrollBehavior 函数:
new VueRouter({模式:'历史',滚动行为:函数(到,从,savedPosition){如果(to.hash){返回{选择器:to.hash}//或者对于Vue 3://返回{el: to.hash}} 别的 {返回 { x: 0, y: 0 }}},路线: [{路径:'/',组件:abcView},//你的路线]});
参考:https://router.vuejs.org/guide/advanced/scroll-behavior.html#async-scrolling
我尝试创建一个 jsFiddle 示例,但由于 mode:'history'
而无法正常工作.如果你复制代码并在本地运行,你会看到它是如何工作的:https://jsfiddle.net/mani04/gucLhzaL/
通过在 scrollBehavior 中返回 {selector: to.hash}
(或 {el: to.hash}
在 Vue 3 中),您将锚标签哈希传递给下一条路线,它将导航到该路线中的相关部分(使用 id
标记).
I am creating a small Vue webapp, I want to create an anchor tag in this.
I have given an id
to one of the div
I wanted to have anchor tags like this:
<div id="for-home">
....
</div>
And here is my router configuration:
export default new Router({
abstract: true,
mode: 'history',
scrollBehavior: () => ({ y: 0 }),
routes: [
{ path: '/', component: abcView}
]
})
But with this anchor tags are sometimes working and sometimes not working, Have I missed something in this?
I believe you are asking about jumping directly to a particular area of page, by navigating to an anchor tag like #section-3
within the page.
For this to work, you need to modify your scrollBehavior function as follows:
new VueRouter({
mode: 'history',
scrollBehavior: function(to, from, savedPosition) {
if (to.hash) {
return {selector: to.hash}
//Or for Vue 3:
//return {el: to.hash}
} else {
return { x: 0, y: 0 }
}
},
routes: [
{path: '/', component: abcView},
// your routes
]
});
Ref: https://router.vuejs.org/guide/advanced/scroll-behavior.html#async-scrolling
I attempted creating a jsFiddle example but it is not working because of mode:'history'
. If you copy the code and run locally, you will see how it works: https://jsfiddle.net/mani04/gucLhzaL/
By returning {selector: to.hash}
(or {el: to.hash}
in Vue 3) in scrollBehavior, you will pass the anchor tag hash to the next route, which will navigate to the relevant section (marked using id
) in that route.
这篇关于如何使用 Vue Router 创建锚标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!