david2tdw / blog

学习记录
1 stars 1 forks source link

[vue] VUE图片懒加载 #191

Open david2tdw opened 4 years ago

david2tdw commented 4 years ago
  1. 新建个vue项目
  2. src/common/js/imgLazy.js
    
    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)
david2tdw commented 4 years ago

或者注册全局指令,不需每个页面再单独引入

main.js

import imgLazy from '@/common/js/imgLazy.js'
Vue.directive('imgLazy', imgLazy)