上个文章写了跨页面的锚点定位,锚点的页面是在mounted里调用的定位到锚点位置,只有新打开此页面时才会执行mounted,所以当前页面内进行点击定位到锚点位置不起作用,解决方法在main.js里的watch里一直监听着URL是否发生变化,如果URL变化就执行锚点定位方法。
效果:
在mian.js中添加
import {goAnchor,GetQueryString} from '../static/js/common.js';
new Vue({
el: '#app',
router,
render: h => h(App),
mounted:function(){//解决跳转到新页面不默认固定在顶部的bug
this.$router.afterEach((to, from, next) => {
window.scrollTo(0, 0)
})
},
methods:{
goAnchor,
GetQueryString,
},
watch:{
'$route.query':function(newVal,oldVal){
var maodian = newVal.maodian;
if(maodian){
this.goAnchor('#'+maodian);
}
}
}
})
mian.js中引入的common.js的内容
//跳