一、原因
1.下面的nextTick函数,当数据更新了,在dom中渲染后,自动执行该函数;
2.由于dom渲染完后,图片还未加载完,只占了个坑(目前获取的offsetTop未包括图片),所以offsetTop高度会出现偏差;
3.offsetTop高度不对时,大多数是图片高度问题
<template>
<div class="detail">
<detail-nav-bar class="detail-nav-bar"
@titleClick="titleClick" />
<scroll class="content"
ref="scroll">
<!--监听图片加载,子组件发送了goodsImgLoad事件-->
<detail-goods-info @goodsImgLoad="goodsImgLoad" />
<detail-param-info ref="param"
:paramInfo="paramInfo" />
<detail-comment-info ref="comment"
:commentInfo="commentInfo" />
<detail-goods-list ref="goodsList"
:goods="recommend" />
</scroll>
</div>
</template>
data() {
return {
titleTopY: []
};
},
created() {
//getDetail是在获取详情页数据,包括图片
getDetail(this.iid).then(res => {
//获取不同组件的offsetTop
this.$nextTick(() => {
this.titleTopY.push(0);
this.titleTopY.push(this.$refs.param.$el.offsetTop-44);//参数组件
this.titleTopY.push(this.$refs.comment.$el.offsetTop-44);//评论组件
this.titleTopY.push(this.$refs.goodsList.$el.offsetTop-44);//商品推荐组件
console.log(this.titleTopY);
});
});
},
二、解决方法
监听图片加载,图片加载时,再进行nextTick的调用(加入debounce防抖)
export default {
//这里进行import引用,包括组件,封装的debounce函数,已省略
name: "detail",
data() {
return {
titleTopY: [],
getTitleTopY: ""
};
},
created() {
this.getTitleTopY = debounce(() => {
this.$nextTick(() => {
//获取不同组件的offsetTop
this.titleTopY.push(0);
this.titleTopY.push(this.$refs.param.$el.offsetTop-44);
this.titleTopY.push(this.$refs.comment.$el.offsetTop-44);
this.titleTopY.push(this.$refs.goodsList.$el.offsetTop-44);
console.log(this.titleTopY);
});
}, 50);
},
mounted() {
},
methods: {
//监听图片加载
goodsImgLoad() {
this.getTitleTopY();
},
}
};