feat 搭建架构骨架
This commit is contained in:
27
src/directives/lazy.ts
Normal file
27
src/directives/lazy.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import type { Directive } from 'vue'
|
||||
|
||||
const observerMap = new WeakMap<Element, IntersectionObserver>()
|
||||
|
||||
/** v-lazy 图片懒加载:v-lazy="图片地址" */
|
||||
const lazy: Directive<Element, string> = {
|
||||
mounted(el, binding) {
|
||||
if (!(el instanceof HTMLImageElement)) return
|
||||
const target = el
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
const entry = entries[0]
|
||||
if (entry?.isIntersecting) {
|
||||
if (binding.value) target.src = binding.value
|
||||
observer.disconnect()
|
||||
observerMap.delete(el)
|
||||
}
|
||||
})
|
||||
observerMap.set(el, observer)
|
||||
observer.observe(el)
|
||||
},
|
||||
unmounted(el) {
|
||||
observerMap.get(el)?.disconnect()
|
||||
observerMap.delete(el)
|
||||
},
|
||||
}
|
||||
|
||||
export default lazy
|
||||
Reference in New Issue
Block a user