Open david2tdw opened 4 years ago
import baseImg from '@/assets/logo.png'
let observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { !entry.target.isLoaded && showImage(entry.target, entry.target.data_src) } }) })
function showImage (el, imgSrc) { const img = new Image() img.src = imgSrc img.onload = function () { el.src = imgSrc el.isLoaded = true } }
export default { inserted (el, binding) { el.src = baseImg el.data_src = binding.value observer.observe(el) } }
3. src/components/lazyload.vue
[30行写一个Vue图片懒加载指令](https://juejin.im/post/6857359743817220104?utm_source=gold_browser_extension)
或者注册全局指令,不需每个页面再单独引入
main.js
import imgLazy from '@/common/js/imgLazy.js' Vue.directive('imgLazy', imgLazy)
let observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { !entry.target.isLoaded && showImage(entry.target, entry.target.data_src) } }) })
function showImage (el, imgSrc) { const img = new Image() img.src = imgSrc img.onload = function () { el.src = imgSrc el.isLoaded = true } }
export default { inserted (el, binding) { el.src = baseImg el.data_src = binding.value observer.observe(el) } }