在Vue 3中使用IntersectionObserver API可以显著提升性能,尤其是在处理大量DOM结构或实现图片懒加载等场景时。以下是关于如何在Vue 3中使用IntersectionObserver的详细步骤: 1. 理解IntersectionObserver API的基本概念和用途 IntersectionObserver是一个浏览器内置的API,用于异步观察目标元素与其祖先元素或顶级文档视窗(viewport)的...
首先,确保在项目中安装了IntersectionObserver相关的依赖。可以使用npm或yarn进行安装: ```bash npm install intersection-observer ``` 或 ```bash yarn add intersection-observer ``` 接下来,在Vue组件中引入IntersectionObserver: ```javascript import { onMounted, ref } from 'vue'; import { IntersectionObserver...
// 创建IntersectionObserver实例 constobserver =newIntersectionObserver((entries, observer) =>{ // 遍历观察的元素 entries.forEach(entry=>{ // 如果元素可见 if(entry.isIntersecting) { // 加载图片 constimg = entry.target; constsrc = img.getAttribute('data-src'); img.setAttribute('src', src); /...
vue3 - 使用IntersectionObserver实现懒加载 1. 基础用法 import { ref, onMounted, onUnmounted } from'vue'//loading-imageconst imgUrl = ref(newURL('/src/assets/loading.png', import.meta.url).href) let observer: IntersectionObserver onMounted(()=>{//注册观察者observer =newIntersectionObserver(entries...
这个功能主要的底层逻辑是是使用IntersectionObserverAPI,IntersectionObserver用于在浏览器中观察元素的可见性和位置变化。它可以帮助开发者实现一些动态行为,如图片的懒加载、无限滚动等。 简单的示例如下: // 创建IntersectionObserver实例 const observer = new IntersectionObserver((entries, observer) => { ...
console.log('onMounted',instance.value) observer.value = uni.createIntersectionObserver(instance.value); // 如果 .ball 出现在 .scroll-view 可视区域,则执行回调 observer.value .relativeTo('.scroll-view') // 第二个参数 定义相交边界 left top right bottom ...
使用指令的DON是否创建好,钩子函数: mounted,onMounted是在组合API时候使用,现在是选项mounted (el, binding) {// 绑定的元素,绑定的值// // 2.创建一个观察对象,来观察当前使用指令得元素constobserve =newIntersectionObserver(([{isIntersecting}]) =>{if(isIntersecting) {// 如果进入了可视区// 谁进入了...
在IntersectionObserver API出现之前,无限滚动的解决方案都依赖于监听scroll事件,为了避免频繁触发scroll事件造成的性能问题,需要手动节流。而通过IntersectionObserver,我们可以更优雅地实现无限滚动。在阅读本文之前可先了解IntersectionObserver和IntersectionObserverEntry, 将有助于理解本文内容 ...
通过vueuse封装的useIntersectionObserver 核心代码: (1)useIntersectionObserver的基本使用 import { useIntersectionObserver } from '@vueuse/core' import { ref } from 'vue' const target = ref<HTMLImageElement | null>(null) // stop停止监听 const { stop } = useIntersectionObserver(target, ([...
import { onMounted, Ref } from "vue"; const options = { // root: document.querySelector(".container"), // 根元素,默认为视口 rootMargin: "0px", // 根元素的边距 threshold: 0.5, // 可见性比例阈值 once: true, }; function callback( entries: IntersectionObserverEntry[], observer: Interse...