主要使用到了IntersectionObserver這一個API https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver/IntersectionObserver
其主要的思路就是:
使用監測是否進入可視區域這一API特性,將原來需要image上的src屬性的值不直接傳給src屬性,而是使用自定義指令v-lazy(其他的也可以,隨便你),將其保存於指令中,一旦監聽到DOM進入可視區域,則將該值賦予所掛在的el的src上。
Vue中自定義指令
const defineDirective = (app) => { //圖片懶加載指令,v-lazy app.directive('lazy', { //Vue2.0用inserted監聽DOM是否創建完畢 //Vue3.0中用mounted mounted(el, binding) { //觀察當前元素 const observer = new IntersectionObserver(([{isIntersecting}]) => { if(isIntersecting){ //v-for生成的多組縱列圖片只進行一次觀察:停止觀察 observer.unobserve(el) //若圖片加載失敗,使用該默認圖片 el.onerror = () => { el.src = defaultImg } //組件使用指令傳來的值進行操作,賦值於src el.src = binding.value } }, { //進入區域立即觀察,一個選項而已 threshold: 0 }) //掛載元素。只進行一次觀察:開始觀察 observer.observe(el) } }) }