一,下载插件
1.npm i @vueuse/core
2. 导入api
import { useIntersectionObserver } from "@vueuse/core"
3.使用api
onMounted(() => {
const { stop } = useIntersectionObserver(refImg.value, ([{ isIntersecting }]) => {
if (isIntersecting) {
refImg.value.src = 'https://img.bosszhipin.com/beijin/mcs/chatphoto/20190411/5a88d3b2b5f52168a6695f534fca4670a722b321da03f08d29a2ecbd23451ef4_s.jpg?x-oss-process=image/resize,w_120,limit_0'
}
console.log(isIntersecting, refImg.value.src);
})
})
封装 v-lazy:
import { useIntersectionObserver } from '@vueuse/core'
import { App } from 'vue'
import defaultImg from '@/assets/images/200.png'
export default {
install(app: App) {
// 全局指令
app.directive('lazy', {
// mounted是v3中自定义指令的生命周期,它会被自动调用
// 它表示的涵义和组件的mounted是一致的
// el 是dom元素, binding
mounted(el,binding) {
// 设置默认图
el.src = defaultImg
// console.log('lazy', el, binding.value)
// 实时监听el是否可见,如果可见,给他的src设置binding.value
const { stop } = useIntersectionObserver(el, ([{isIntersecting}]) => {
if(isIntersecting) {
el.src = binding.value
// 停止
stop()
}
})
// el是img标签
// el.onerror 0级dom事件
// el.onclick = () =>
// el.addEventListener('click')
// el.onerror = () => {
// }
el.addEventListener('error', () => {
// console.log('失败11111')
// 设置默认图
el.src = defaultImg
})
}
})
}
}