在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}×tamp=${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