如何用Vue Router创建锚点标签 [英] How to create anchor tags with Vue Router
问题描述
我正在创建一个小 Vue webapp,我想在此创建一个定位标记。
我为 div
中的一个提供了 id
这样的锚点标签:
< div id =for-home>
....
< / div>
以下是我的路由器配置:
<$ ($ {
abstract:true,
mode:'history',
scrollBehavior:()=>({y:0,p $ p> }),
routes:[
{path:'/',component:abcView}
]
})
但是有了这个锚点标签有时候可以工作,有时候并不工作,我错过了什么?
我相信你正在询问如何直接跳转到页面的特定区域,方法是导航到像#section-3这样的锚定标记
为此,您需要修改scrollBehavior功能,如下所示:
$ prev =lang-js prettyprint-override>
new VueRouter({
mode:'history',
scrollBehavior:function(to,from,savedPosition) {
if(to.hash){
return {selector:to.hash}
} else {
return {x:0,y:0}
}
},
routes:[
{path:'/', component:abcView},
// your routes
]
});
参考: http://router.vuejs.org/en/advanced/scroll-behavior.html
我试图创建一个jsFiddle示例,但它不工作,因为模式:'history'
。如果您复制代码并在本地运行,您将看到它的工作原理: https://jsfiddle.net/mani04/ gucLhzaL /
通过在scrollBehavior中返回 {selector:to.hash}
,您将传递将标签哈希锚定到下一个路线,该路线将导航到该路线中的相关路段(标记为 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}
} else {
return { x: 0, y: 0 }
}
},
routes: [
{path: '/', component: abcView},
// your routes
]
});
Ref: http://router.vuejs.org/en/advanced/scroll-behavior.html
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}
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屋!