vue3中-实现组件数据懒加载

216 阅读1分钟
  1. 首先下载@vueuse/core
yarn add @vueuse/core
  1. 封装一个hooks函数 我将其封装在src/hooks/index.js中 代码如下
// hooks 封装逻辑,提供响应式数据。
import { useIntersectionObserver } from '@vueuse/core'
import { ref } from 'vue'
// 数据懒加载函数
export const useLazyData = (apiFn) => {
  // 需要
  // 1. 被观察的对象
  // 2. 不同的API函数
  const target = ref(null)
  const result = ref([])
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        stop()
        // 调用API获取数据
        apiFn().then(data => {
          result.value = data.result
        })
      }
    }
  )
  // 返回--->数据(dom,后台数据)
  return { target, result }
}
  1. 使用方法
//你所请求api
import { findNew } from '@/api/home'
+import { useLazyData } from '@/hooks'//引入钩子函数
export default {
  name: 'HomeNew',
  components: { HomePanel, HomeSkeleton },
  setup () {
  //target 绑定要懒加载的dom标签上
  //result 是请求回来data里面的result 具体请和后台确认字段名
+    const { target, result } = useLazyData(findNew)
//把result的参数赋值给goods
+    return { goods: result, target }
  }
}
  1. dom绑定的方法
<div ref="target" style="position: relative;height: 426px;">

总结1、下插件;2、封装勾子;3、引入;4、绑定