Vue元件利用better-scroll滾動時,offsetTop高度計算問題
阿新 • • 發佈:2020-08-02
一、原因
<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); }); }); },
1.上面的nextTick函式,當資料更新了,在dom中渲染後,自動執行該函式;
2.由於dom渲染完後,圖片還未載入完,只佔了個坑(目前獲取的offsetTop未包括圖片),所以offsetTop高度會出現偏差;
3.offsetTop高度不對時,大多數是圖片高度問題
二、解決方法
監聽圖片載入,圖片載入時,再進行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(); }, } };