Home >Web Front-end >JS Tutorial >Detailed explanation of scrolling behavior of Vue-Router

Detailed explanation of scrolling behavior of Vue-Router

php中世界最好的语言
php中世界最好的语言Original
2018-04-17 11:18:281779browse

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:

    { x: number, y: number }
  • { selector: string }
  • If a false boolean value is returned, or an empty object is returned, no scrolling will occur.

Example:

scrollBehavior (to, from, savedPosition) {
 return { x: 0, y: 0 }
}
For all route navigation, simply let the page scroll to the top.

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.js


How to use the Particles.js library in vue


The 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn