Vue3 & TypeScript ---- 自定义指令v-lazyload

首先,我有一个问题。。。如果使用指令的元素已被销毁,那么之前设置的观测器还有必要unobserve()吗?会不会因为这个东西本身就是附着在元素上的,元素都没了,它就没了。没都没了,就没必要取消监测了?我想应该是这样的。。。

其次,还有一个问题。。。在directive的指令钩子中,假如在mounted中设置了一个变量,我想在beforeUnmount中使用 ,根据官方文档,咱只能这么整。。爸特,爸特!遇到了像这种实例,它JSON.stringify之后根本就啥也不是了呀
钩子之间传值
不过。。不过。。。如果头一个问题没有的话,第二问题它就不存在了嘿嘿

提前告知,我这个简单用用行,但是一个页面中如果用多一定有问题。。慎用哈哈哈哈哈哈哈哈哈哈哈哈我请教过大佬之后会回来修改的~
在创建一个新的观测器的时候把它推到一个数组里,离开页面或者元素onobserve()后会给它删除。我忘记是为啥了,好像有个插件 vue3-lazyload 就整了这么一出儿

点:

代码:

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]);
})

~~~tada~一个图片懒加载的自定义指令就完成啦

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容