Vue添加锚点(兼容直接输入地址时scrollBehavior不

2020-09-17  本文已影响0人  努力study代码的小哪吒
Vue添加锚点有很多方法,今天我们来说vue-router提供的一种

vue-router官网说明
锚点就是在链接中有#号的一个东西,我们可以通过router去做

const ROUTER_CONFIG = {
  mode: 'history',
  scrollBehavior (to, from, savedPosition) {
    if (to.hash) {
      console.log('hash', to.hash)
      return {
        selector: to.hash
      }
    }
  }
}
// 但是scrollBehavior使用时,前提是你的mode设置为history

这个方法因为是通过路由,但是假如我们直接输入地址的话,就不走这个方法了,所以需要我们自己写一个,其实location也提供给我们相应的监听hash的字段了

mounted () {
    const hash = location.hash
    if (hash) {
      const id = hash.split('#')[1]
      const ele = document.getElementById(id)
      setTimeout(() => {
        ele && ele.scrollIntoView(true)
      })
    }
  },

我们的view层代码

<div class="btn" :id="active.id === 2 ? 'coupon' : ''" @click="goTo(active.id)">
    {{ active.btnTitle }}
</div>

这样就可以都兼容了,无论是通过路由还是通过直接输入的链接都是可以正常锚点到的

上一篇下一篇

猜你喜欢

热点阅读