当前位置: 代码迷 >> 综合 >> vue3 基于自定义指令实现懒加载图片
  详细解决方案

vue3 基于自定义指令实现懒加载图片

热度:95   发布时间:2023-11-18 12:48:48.0

  

<!-- 新闻列表 --><div class="skeleton" v-if="trendingList.length === 0"><img src="@/assets/images/skeleton.png" alt="" /></div><div class="flow-list-container" v-else><ul class="flow-list-ul"><liv-for="item in trendingList":class="`note-flow ${item.list_image_url ? 'have-img' : ''}`":key="item.id"><router-link :to="`/detail/${item.slug}`"><div class="summary"><h6 class="title">{
   { item.title }}</h6><p class="abstract">{
   { item.public_abbr }}</p></div><divclass="wrap-img"v-if="item.list_image_url"v-lazyimg="item.list_image_url"><img src="" alt="" /></div></router-link></li></ul><div class="flow-list-placeholder-load-more" @click="handleMore">展开更多文章<i class="ic-show"></i></div></div>

main.js

import {createApp
} from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import directive from './directive';const app = createApp(App);
app.use(router);
app.use(store);
directive(app);
app.mount('#app');

 directive.js

export default function directive(app) {// 图片延迟加载let ob = new IntersectionObserver(changes => {changes.forEach(item => {let {target,isIntersecting} = item;if (!isIntersecting) return;target.$imgBox.src = target.$src;target.$imgBox.style.opacity = 1;ob.unobserve(target);});}, {threshold: [0.5]});app.directive('lazyimg', {mounted(el, binding) {let imgBox = el.querySelector('img');if (!imgBox) return;imgBox.src = '';imgBox.style.opacity = 0;imgBox.style.transition = 'opacity .3s';el.$src = binding.value;el.$imgBox = imgBox;ob.observe(el);}});
};