上报商品曝光

在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: null, // 未传入 root 或其值为null,则默认使用顶级文档的视口
        rootMargin: '0px',
        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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容