上报商品曝光

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

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

给组件添加进入视图监听


    viewTrack() {
      // 创建观察者
      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', // 当前元素允许超出屏幕的范围,上和左右允许超出屏幕,防止运营设置x为负值导致不会上报,要和root搭配使用才有效
        threshold: 0.1 // 当10%的元素可见时触发
      })
  
      // 开始观察目标元素
      this.observer.observe(this.$el);
    },

执行上报

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);
  // 可选:设置延时后移除img元素
  setTimeout(() => {
    document.body.removeChild(img);
  }, 1000);
}

destroy停止观察监听

  beforeDestroy() {
    // 组件卸载时停止观察
    if (this.observer) {
      this.observer.disconnect()
    }
  },

兼容性处理

// main.js

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容