Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  171] [ 1]  / answers: 1 / hits: 33117  / 8 Years ago, mon, october 31, 2016, 12:00:00

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?


More From » html

 Answers
61

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.


[#60237] Wednesday, October 26, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dayanaracolleeng

Total Points: 7
Total Questions: 96
Total Answers: 104

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
;