组件懒加载
作用及原理:当所需的组件进入到可视区域(例如新鲜好物及人气热榜)后才会发请求获取数据,这样可以优化性能
步骤
下包
yarn add @vueuse/core
导包,使用其中的useIntersectionObserver函数
import { useIntersectionObserver } from '@vueuse/core'
设置监听器
setup(){
const target = ref(null)
// stop是一个可以停止监听的函数
const { stop } = useIntersectionObserver(
target, // target就是监测的dom
// isIntersecting是布尔值,检测被监测的元素是否进入可视区,如果进入可视区则为true,否则为false
([{ isIntersecting }], observerElement) => {
// 当进入可视区后进行发请求渲染组件,并且关闭监听
if (isIntersecting) {
// 发请求的函数
getNewList()
stop()
}
}
)
return { newList, target }
}
使用ref绑定组件
<HomePanel ref="target" > </HomePanel>
图片懒加载
作用及原理:监听图片进入到可视区域,图片根据src中的地址进行请求,渲染页面,作用优化性能
- 原先在组件中发送请求时,进行了数据懒加载,当组件进入到可视区,获取到src的数据,但是渲染图片,还需要根据数据进行寻找请求,那么图片懒加载就可以,当你进来的时候才进行根据地址寻找请求渲染的过程
步骤
使用自定义指令,在main.js中进行挂载
import directivePlugin from '@/directives/index'
createApp(App).use(componentPlugin).use(directivePlugin).use(store).use(router).mount('#app')
同样使用监听器当图片区域进入到可视区域,执行渲染
import { useIntersectionObserver } from '@vueuse/core'
import defaultImg from '../assets/images/200.png'
export default {
install (app) {
// 语法app.directive('指令名',{})
app.directive('imgLazy', {
mounted (el, binding) {
const { stop } = useIntersectionObserver(
el,
([{ isIntersecting }], observerElement) => {
if (isIntersecting) {
// 当图片加载无效时,显示默认图片
el.onerror = () => {
el.src = defaultImg
}
// 否则直接显示即可
el.src = binding.value
stop()
}
}
)
}
})
}
}
在img中绑定自定义指令
<img v-imgLazy="item.picture" :src="item.picture" alt="">
\