vue3.0组件数据懒加载

707 阅读1分钟

原因:点击网站 一股脑发送请求全部渲染 浪费性能

解决:可见区域发送请求 不可见不发送

我们可以使用 @vueuse/core 中的 useIntersectionObserver 来实现监听组件进入可视区域行为,需要配合vue3.0的组合API的方式才能实现

请求数据懒加载

import { useIntersectionObserver } from '@vueuse/core'
import { ref } from 'vue-demi'
export function useIntersection (reqFn) {
  const target = ref()
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }]) => {
      if (isIntersecting) {
        console.log('进入可视区')
        reqFn()
        stop()
      }
    },
    // 进入当前元素可视区域的比例是多少才执行回调 0-1 值越大 代表需要进入的面积越大
    { threshold: 0 }
  )
  return { target }
}
​

使用


  <div class="home-product" ref="target">
  //target进入可视区域再发送请求
  const { target } = useIntersection(getGoods)

图片渲染懒加载

自定义指令

// 引入监听是否进入视口
import { useIntersectionObserver } from '@vueuse/core'
import defaltImg from '@/assets/images/loading.gif'
const imgLazy = {
  mounted (el, binding) {
    const { stop } = useIntersectionObserver(
      el,
      ([{ isIntersecting }]) => {
        // 进入可视区
        if (isIntersecting) {
          // 添加loading图片
          el.src = defaltImg
          setTimeout(() => {
            el.src = binding.value
          }, 500)
​
          el.onerror = () => {
            el.src = defaltImg
          }
          stop()
        }
      },
      { threshold: 0.5 }
    )
  }
}
​
export default {
  install (app) {
    app.directive('imgLazy', imgLazy)
  }
}

1.减少浏览器压力 高性能

2.减少图片请求次数 减少浏览器压力