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)到的