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

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>

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。