首先,我有一个问题。。。如果使用指令的元素已被销毁,那么之前设置的观测器还有必要unobserve()吗?会不会因为这个东西本身就是附着在元素上的,元素都没了,它就没了。没都没了,就没必要取消监测了?我想应该是这样的。。。
提前告知,我这个简单用用行,但是一个页面中如果用多一定有问题。。慎用哈哈哈哈哈哈哈哈哈哈哈哈我请教过大佬之后会回来修改的~
在创建一个新的观测器的时候把它推到一个数组里,离开页面或者元素onobserve()后会给它删除。我忘记是为啥了,好像有个插件 vue3-lazyload 就整了这么一出儿
点:
- Vue3自定义指令:https://cn.vuejs.org/guide/reusability/custom-directives.html
- intersection.Observer:https://developer.mozilla.org/zh-CN/docs/Web/API/Intersection_Observer_API
-
上面那个实例会返回一些 IntersectionObserverEntry 这个东西,它里面有一些东西
- 上图我们选择不使用参数isIntersecting或者intersectionRatio来判断,是因为想提前加载马上就要加载到位置的图片,相当于预留出一些滑动时间,在快要划到元素的时候提前加载它的图片
-
文件层级
代码:
lazyload.ts ↓
import { DirectiveBinding } from 'vue';
import { getUuid } from '@/utils'
const cache = [];
export default {
mounted(el: HTMLImageElement, binding: DirectiveBinding) {
const intersectionObserver = new IntersectionObserver((entries: IntersectionObserverEntry[]) => {
const image = entries[0];
console.log(image,'00000000000000000000')
// 元素距离视图顶部的距离
const elTop = image.boundingClientRect.y;
// 视图高度
const rootHeight = image.rootBounds.height;
// 不直接使用 intersectionRatio 或 isIntersecting,提前加载快要加载到的图片
if (elTop < rootHeight) {
// 多加载一屏半
el.src = binding.value;
intersectionObserver.unobserve(el);
if (cache.length > 0) {
const index = cache.findIndex(item => item.dataid === el.getAttribute('dataid'));
cache.splice(index, 1);
}
}
})
const dataid = getUuid();
el.setAttribute('dataid', dataid);
cache.push({
observer: intersectionObserver,
dataid
});
intersectionObserver.observe(el);
},
// 在元素卸载之前,先将它身上的观测器取消观测,接着将存在数组中的观测器删除
beforeUnmount(el: HTMLImageElement) {
console.log(el,'还有ELELELELELELELELEEL吗')
if (cache.length > 0) {
const index = cache.findIndex(item => item.dataid === el.getAttribute('dataid'));
cache[index].observer.unobserve(el);
cache[index].observer = null;
cache.splice(index, 1);
}
}
}
getUuid() ↓
export const getUuid = (len = 16, radix = 16) => {
const chars =
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
const uuid = []
let i: number;
radix = radix || chars.length
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
} else {
// rfc4122, version 4 form
let r: number;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
uuid[14] = '4'
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | (Math.random() * 16)
uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r]
}
}
}
return uuid.join('')
}
directive --> index.ts ↓
import lazyload from './lazyload'
const directiveList = {
lazyload
}
export default directiveList;
main.ts ↓
import { createApp } from 'vue'
import App from './App.vue'
import directives from '@/directives'
const app = createApp(App)
Object.keys(directives).forEach(key => {
app.directive(key, directives[key]);
})