vue2路由之指定滑动位置scrollBehavior

看源码的时候看到这个属性:

 

 

新手自然不知道这个是什么东西了,查了下vue  API:

https://router.vuejs.org/en/advanced/scroll-behavior.html

上面这个的意思就是当转到一个新的页面时,定位到最顶端。

Scroll Behavior

When using client-side routing, we may want to scroll to top when navigating to a new route, or preserve the scrolling position of history entries just like real page reload does. vue-router allows you to achieve these and even better, allows you to completely customize the scroll behavior on route navigation.

Note: this feature only works in HTML5 history mode.

When creating the router instance, you can provide the scrollBehavior function:

const router = new VueRouter({
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
    // return desired position
  }
})

The scrollBehavior function receives the to and from route objects. The third argument, savedPosition, is only available if this is a popstate navigation (triggered by the browser's back/forward buttons).

The function can return a scroll position object. The object could be in the form of:

  • { x: number, y: number }
  • { selector: string }

If a falsy value or an empty object is returned, no scrolling will happen.

For example:

scrollBehavior (to, from, savedPosition) {
  return { x: 0, y: 0 }
}

This will simply make the page scroll to top for all route navigations.

Returning the savedPosition will result in a native-like behavior when navigating with back/forward buttons:

scrollBehavior (to, from, savedPosition) {
  if (savedPosition) {
    return savedPosition
  } else {
    return { x: 0, y: 0 } } } 

If you want to simulate the "scroll to anchor" behavior:

scrollBehavior (to, from, savedPosition) {
  if (to.hash) {
    return {
      selector: to.hash
    }
  }
}

We can also use route meta fields to implement fine-grained scroll behavior control. Check out a full example here.

 

转载于:https://www.cnblogs.com/guazi/p/6759323.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值