1. Borrow plug-ins
@vueuse/core
The underlying principle of the plugin uses # IntersectionObserver() in H5.
For details, see IntersectionObserver
npm i @vueuse/core
Copy the code
2. Reference plug-ins
import { useIntersectionObserver } from '@vueuse/core'
Copy the code
Use 3.
<template> <div ref="target"></div> </template> <script> export default{setup(){const target = ref(null) // Reference the target Const {stop} = useIntersectionObserver(target, // Target is an object reference to vUE. Is the target of observation // Whether isIntersecting enters the visible area, // observerElement observed dom ([{isIntersecting}], ObserverElement) => {// At this point, isIntersecting can be used to determine whether DOM elements are within the intersecting area, and then do business if (isIntersecting) {// 1. Return {list, target}}} </script>Copy the code
4. Encapsulate lazy data loading
Here we put this file into the sample solution /index.js
Import {useIntersectionObserver} from '@vueuse/core' import {ref} from 'vue' /** * Lazy loading of data * @param {*} fn Calls the function once when the target is visible * @returns target: */ export function useLazyData (fn) {const target = ref(null) // const {stop} = UseIntersectionObserver (target, // Target is an object reference to vUE. Is the target of observation // Whether isIntersecting enters the visible area, // DOM ([{isIntersecting}], observerElement) => {// It can be judged by isIntersecting. Then do business if (isIntersecting) {// 1. Fn ()}}, // threshold is the ratio of visible area, default is 1/10 // The current element in the page display ratio is less than 1/10, there will be white screen {threshold: 0 } ) return target }Copy the code
5. Lazy loading with encapsulated data
<template>
<div ref="target"></div>
</template>
Copy the code
import { useLazyData } from '@/compositions/index.js' <script> setup () { const goods = ref([]) const fn = () => { Const target = useLazyData(fn) return {goods, target}} </script>Copy the code