需求
在菜单A页面点击某个元素携带id跳转到B详情页面,B页面获取该id元素的offsetTop, 并自动滚动到该元素处
问题
跳转到B详情页面, 在mounted获取到document.getElementById(a)为null, 因为整个详情页面是从后端获取来渲染的数据, 因此此时dom元素还未渲染出来, 所以拿到的是null, 但是尝试过以下两种办法均无效:
- this.$nextTick(function() {}) 在这里获取dom, 无效
- 在接口请求完成后再获取元素, 无效
- 在created请求接口, mounted获取元素, 无效
mounted() {
this.id = this.$route.params.id;
let a = "section" + this.id;
var top = document.getElementById(a).offsetTop;
$(window).scrollTop(top + 300);
$("#myNav").affix({
offset: {
top: 300
}
});
},
解决
还是得用上计时器做点延迟才行…
mounted() {
setTimeout(() => {
this.id = this.$route.params.id;
let a = "section" + this.id;
var top = document.getElementById(a).offsetTop;
$(window).scrollTop(top + 300);
$("#myNav").affix({
offset: {
top: 300
}
});
var wow = new WOW();
wow.init();
}, 300);
},