 图片懒加载自定义指令
图片懒加载自定义指令
 # 图片懒加载
扩展 vue 的原有功能 , 顶一个图片懒加载指令
带有默认导出 install()  函数的 js 文件可为 vue 安装自定义插件
# 代码
// 导入图片默认显示图片
import defaultImg from '@/assets/images/200.png'
export default {
  // 安装插件函数 vue3使用 app 应用实例,vue2 使用Vue构造函数
  install (app) {
    // 定义指令
    defineDirective(app)
  }
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
在 main.js 中注册使用
import UI from '@/components/library'
createApp(App).use(store).use(router).use(UI).mount('#app')
1
2
2
图片懒加载指令代码
const defineDirective = (app) => {
    // vue 自定义指令
    app.directive('lazy', {
        mounted (el, binding) {//监听DOM是否创建好的函数
            //创建监听函数
        	 const observe = new IntersectionObserver(([{ isIntersecting }])=>{
                 if (isIntersecting) {
                    //停止监听
                    observe.unobserve(el)
                    //出错设置为默认图片
                    el.onerror = ()=>{
                        el.src = defaultImg
                    }
                    //未出错绑定加载图片地址
                    el.src = binding
                 }
             },{thrashold:0})
             //开启观察
             observe.observe(el)
        }
    })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 参数解释
- el监听的元素
- binding传入的值
- isIntersecting监听元素是否进入可视区
- thrashold可视区相交为 0
# 使用
<img v-lazy="cate.picture" alt="">
1
编辑  (opens new window)
  上次更新: 2023/02/07, 14:51:48
