Vue添加錨點(diǎn)(兼容直接輸入地址時(shí)scrollBehavior不觸發(fā))

Vue添加錨點(diǎn)有很多方法,今天我們來說vue-router提供的一種

vue-router官網(wǎng)說明
錨點(diǎn)就是在鏈接中有#號的一個(gè)東西,我們可以通過router去做

const ROUTER_CONFIG = {
  mode: 'history',
  scrollBehavior (to, from, savedPosition) {
    if (to.hash) {
      console.log('hash', to.hash)
      return {
        selector: to.hash
      }
    }
  }
}
// 但是scrollBehavior使用時(shí),前提是你的mode設(shè)置為history

這個(gè)方法因?yàn)槭峭ㄟ^路由,但是假如我們直接輸入地址的話,就不走這個(gè)方法了,所以需要我們自己寫一個(gè),其實(shí)location也提供給我們相應(yīng)的監(jiān)聽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>

這樣就可以都兼容了,無論是通過路由還是通過直接輸入的鏈接都是可以正常錨點(diǎn)到的

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容