上報商品曝光

在mounted組件渲染完成后添加方法

  mounted() {
    this.viewTrack();
  },

給組件添加進入視圖監(jiān)聽


    viewTrack() {
      // 創(chuàng)建觀察者
      this.observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            this.trackFetchAction();
            this.observer.unobserve(entry.target);
            console.log('元素進入視口')
          } else {
            console.log('元素離開視口')
          }
        })
      }, {
        // 可選的配置選項
        root: document.getElementById('clientWarp'), // 未傳入 root 或其值為null,則默認使用頂級文檔的視口
        rootMargin: '30px 100px 0px 100px', // 當前元素允許超出屏幕的范圍,上和左右允許超出屏幕,防止運營設(shè)置x為負值導(dǎo)致不會上報,要和root搭配使用才有效
        threshold: 0.1 // 當10%的元素可見時觸發(fā)
      })
  
      // 開始觀察目標元素
      this.observer.observe(this.$el);
    },

執(zhí)行上報

trackFetchAction() {
  const productId = 'productId'; // todo 修改為自己的商品id
  const img = new Image();
  img.src = `https://your-analytics-domain.com/exposure?product_id=${productId}&timestamp=${Date.now()}`;
  img.style.display = 'none';
  document.body.appendChild(img);
  // 可選:設(shè)置延時后移除img元素
  setTimeout(() => {
    document.body.removeChild(img);
  }, 1000);
}

destroy停止觀察監(jiān)聽

  beforeDestroy() {
    // 組件卸載時停止觀察
    if (this.observer) {
      this.observer.disconnect()
    }
  },

兼容性處理

// main.js

import 'intersection-observer' // 引入 Intersection Observer polyfill

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容