一、原因
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();
},
}
};