This time I will bring you the scrolling behavior of Vue-Router Detailed explanation of use, what are the precautions when using Vue-Router scrolling behavior, the following is a practical case, Let’s take a look.
Scroll behavior
Using front-end routing, when switching to a new route, you want the page to scroll to the top, or to maintain the original scroll position, just like reloading the page. vue-router can do it, but better. It allows you to customize how the page scrolls when routing is switched.
Note:This feature is only available in HTML5 history mode. When creating a Router instance, you can provide a scrollBehavior method:
var router = new VueRouter({ routes: [...], scrollBehavior (to, from, savedPosition) { // return 期望滚动到哪个的位置 } })
The scrollBehavior method receives to and from routing objects. The third parameter savedPosition is available only if popstate
Navigation(triggered by the browser's forward/back buttons). This method returns the object information of the scroll position, which looks like this:
Example:
scrollBehavior (to, from, savedPosition) {
return { x: 0, y: 0 }
}
Return to savedPosition, when pressing the back/forward button, it will behave like the browser's native behavior:
scrollBehavior (to, from, savedPosition) { if (savedPosition) { return savedPosition } else { return { x: 0, y: 0 } } }
If you want to simulate the behavior of "scroll to anchor":
scrollBehavior (to, from, savedPosition) { if (to.hash) { return { selector: to.hash } } }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
Detailed explanation of the use of Three.jsHow to use the Particles.js library in vueThe above is the detailed content of Detailed explanation of scrolling behavior of Vue-Router. For more information, please follow other related articles on the PHP Chinese website!