How to simulate "scroll to anchor" when loading a page in Vue Router?

I have a small Vue.js SPA with the following router configuration taken from docs :

export default new VueRouter({ routes, // defined above... mode: 'history', scrollBehavior(to, from, savedPosition) { if (to.hash) { return { selector: to.hash } } else if (savedPosition) { return savedPosition; } else { return { x: 0, y: 0 } } } }) 

Consider the link on the main page:

 <router-link to="#services">Services</router-link> 

It jumps to the anchor element <div id="services">...</div> as expected. However, when you activate the link, then scroll down the page from #services and refresh the page, you will return to #services not . You will remain in the same place where you left off, although the URL will still contain a hash (for example, in the form app.dev/#services ).

How to configure the router so that when the page loads, it leads the user to the anchor element, given that the URL contains its hash (and, well, this hash corresponds to a valid existing element)?

+5
source share
1 answer

I had the same problem, but I also wanted to have an animated hash scroll. I was able to test both functions with vue-scrollto . https://github.com/rigor789/vue-scrollto

Something like this should work.

 // import import VueScrollTo from 'vue-scrollto'; //... scrollBehavior(to, from, savedPosition) { if (to.hash) { VueScrollTo.scrollTo(to.hash, 700); return { selector: to.hash } } else if (savedPosition) { return savedPosition; } else { return { x: 0, y: 0 } } } 

Thus, it always animates the hash. If you do not want to animate, use 0 as time instead of 700 . If you do not like to use this module, you can manually jump to the anchor using regular javascript using the methods described here

0
source

Source: https://habr.com/ru/post/1269572/


All Articles