1.新建directives文件夹,里面新建index.ts文件 自定义指令
const defineDirective = (app: any) => {
app.directive('mylazy', {
mounted(el: HTMLImageElement, bindings: any) {
const oberver = new IntersectionObserver(([{ isIntersecting }]) => {
if (isIntersecting) {
el.src = bindings.value
oberver.unobserve(el)
el.onerror = () => {
el.src = 'https://img-blog.csdnimg.cn/img_convert/32bbcc4fe8a7f33a88ea7579fe052087.png'
}
}
})
oberver.observe(el)
},
})
}
export default {
install(app: any) {
defineDirective(app)
},
}
main.ts全局引入
import { createApp } from 'vue'
import App from './App.vue'
import mylazy from '@/directives/index'
createApp(App)
.use(mylazy)
.mount('#app')
使用
<template>
<div class="img-container">
<img v-mylazy="url" alt="" v-for="url in state.urls" :key="url" />
</div>
</template>
<script lang="ts" setup>
import { ref, reactive } from "vue";
import img1 from "@/assets/1.webp";
import img2 from "@/assets/2.webp";
import img3 from "@/assets/3.webp";
import img4 from "@/assets/4.webp";
import img5 from "@/assets/5.webp";
import img6 from "@/assets/6.webp";
const state = reactive({
urls: [img1, img2, img3, img4, img5, img6],
});
</script>
<style scoped lang="scss">
img {
display: block;
width: 50vw;
height: 50vh;
}
</style>