scrollBehavior实现滚动到固定位置

464 阅读1分钟

1、当创建一个router实例,可以提供一个 scrollBehavior 方法

const router = new VueRouter({
  mode: 'history',
  routes,
  scrollBehavior(to, from, savedPosition) {
    console.log(to, from, savedPosition)
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})

返回 savedPosition,在按下前进/后退按钮时,可以使滚动条停留在离开时的位置上

2、模拟 滚动到锚点 的行为 路径上添加锚点

{ text: '首页', path: '/home#p' }

页面中设置锚点元素

    <p id="p">我是p标签</p>

通过判断hash,跳转至锚点的位置上

const router = new VueRouter({
  mode: 'history',
  routes,
  scrollBehavior(to, from, savedPosition) {
    console.log(to, from, savedPosition)
    // if (savedPosition) {
    //   return savedPosition
    // } else {
    //   return { x: 0, y: 0 }
    // }
    if (to.hash) return { selector: to.hash }
  }
})