通过vue3.0自定义指令完成图片懒加载功能
用到vue自定义功能,IntersectionObserver的api
IntersectionObserver这个api的具体用法MDN 阮一峰博客
js部分
- index.js部分
// 外部引入lazyload的js文件
import lazyload from './lazyload'
let LazyPlugin = {}
LazyPlugin.install = (Vue) => {
Vue.directive('lazy', lazyload)
}
export default LazyPlugin
- lazyload.js
export default {
mounted(el, binding) {
let io = new IntersectionObserver(entries => {
entries.forEach(entry => {
let lazyImage = entry.target;
if (entry.intersectionRatio > 0) {
lazyImage.src = binding.value;
io.unobserve(lazyImage);
}
});
});
io.observe(el);
}
- 在main.js中使用(vue3.0)
import {createApp} from "vue";
import App from "./App.vue";
import LazyPlugin from './lazyPlugin'
createApp(App)
.use(LazyPlugin)
.mount("#app");
html中使用
<div class="mv" v-for="(item, i) in mvList" :key="i">
<img src="../../assets/img/湖边星空.png" v-lazy="item.cover" alt />
</div>