lazy-load
lazy-load copied to clipboard
How to display images in rich text content?
1、How to display images in rich text content? 2、show error
Uncaught (in promise) TypeError: Cannot destructure property 'selector' of 'lazyLoadOptions' as it is undefined.
at useLazyLoad (useLazyLoad.mjs:6:11)
at setup ([id].vue:29:1)
// package.json
"@nuxt-modules/lazy-load": "^0.2.0",
//nuxt.config.ts
buildModules: [
['@nuxt-modules/lazy-load', {
// Options
}]
],
// [id].vue
const { init } = useLazyLoad();
onMounted(() => {
init()
})
same problem
same problem
Try this
// /plugins/lazy-load-img.ts
/**
* 图片懒加载
*/
const lazyLoadImg = () => {
let viewHeight = document.documentElement.clientHeight
let limg = document.querySelectorAll("img[data-src]")
Array.prototype.forEach.call(limg, function (item, index) {
let rect;
if (item.getAttribute("data-src") === "") return
//getBoundingClientRect
rect = item.getBoundingClientRect();
if (rect.bottom >= 0 && rect.top < viewHeight) {
(function () {
let img = new Image()
img.src = item.getAttribute("data-src")
item.src = img.src
item.removeAttribute('data-src')
item.setAttribute("class","loaded")
})()
}
})
}
// 定义一个防抖函数
const debounce = (fn, delay = 500) => {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
const lazyLoad = debounce(lazyLoadImg)
export default lazyLoad
// [id].vue
import lazyLoad from "@/plugins/lazy-load-img"
onMounted(() => {
setTimeout(() => {
lazyLoad()
},100)
window.addEventListener('scroll',lazyLoad,false)
})
onUnmounted(() => {
window.removeEventListener('scroll',lazyLoad,false)
})