美文网首页
Vue添加锚点(兼容直接输入地址时scrollBehavior不

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

作者: 努力study代码的小哪吒 | 来源:发表于2020-09-17 10:52 被阅读0次
    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>
    

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

    相关文章

      网友评论

          本文标题:Vue添加锚点(兼容直接输入地址时scrollBehavior不

          本文链接:https://www.haomeiwen.com/subject/voqlyktx.html