1.先記錄一下非跨頁面的實現方法:
官方文檔有寫,這樣在一個組件裏改變hash,比如#anchor-1,
就能夠跳到id爲anchor-1的位置
router.js中添加
mode: 'history',
srcollBehavior(to,from,savedPosition){
if(to.hash){
return {
selector:to.hash
}
}}
2.但是如果我們要做頁面跳轉時的錨點,
比如 a組件點擊 pageb#anchor-1跳轉到b組件,b組件需要根據hash跳轉到指定位置,就不能用上面的方法了。
可以如下實現:
在b組件內添加一個方法:
goAnchor(selector) {
let anchor = this.$el.querySelector(selector)
document.documentElement.scrollTop = anchor.offsetTop
},
#這裏是根據root 節點來scroll,可以自己根據需要調整scroll對象
在b組件的mounted中添加
this.$nextTick(()=>[
this.goAnchor(window.location.hash)
])
這樣跳轉到靜態頁面是沒有問題了
但是如果
b組建執行錨點的地方是通過ajax獲取數據,v-for渲染的,這樣在goAnchor方法中是獲取不到anchor節點的,需要等待渲染完成。我們可以通過watch來觀察數據是否加載完畢
data() {
return {
items:[] #通過ajax獲取
}
},
watch:{
items:function () {
this.$nextTick(()=>[
this.goAnchor(window.location.hash)
])
}
},
這樣就能解決跨頁面的錨點問題