Vue3-图片懒加载

7/18/2020 vue3

安装

yarn create vite vue3-derective-imglazy

yarn add @vueuse/core

yarn 

yarn dev
1
2
3
4
5
6
7

App.vue

<script setup>
const url = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F4k%2Fs%2F02%2F2109242332225H9-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1663746764&t=6a7897a2a6f0bb8eb90d48e4f90d2076'
</script>

<template>
  <div class="other-context">其他内容</div>
  <div class="img-box">
    <img v-img-lazy="url" />
  </div>
</template>

<style scoped>
.other-context{
  height: 1200px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 20px;
}
.img-box img{
  width: 400px;
  height: 400px;
  background-color: #ccc;
}
</style>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

main.js


import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import { useIntersectionObserver } from '@vueuse/core'

const app = createApp(App)

// 全局指令注册
app.directive('img-lazy', {
  // 指令挂载之后自动执行
  mounted (el, binding) {
    // el: 指令挂载到哪个元素 dom上
    // binding: value 指令值
    console.log(el, binding)
    /*
      1.stop 一个可执行的函数用来停止监听行为
      2.target 一个由ref api调用之后形成的RefImpl对象 也可以是一个dom对象
      3.isIntersecting 一个类型为布尔值的数据 当被监听元素进入视口区域时为true,离开视口区域时为false
      特别注意: 对于目标target是否进入视口区域的监听会一直进行不会只监听一次
    */
    const { stop } = useIntersectionObserver(
      el,
      ([{ isIntersecting }], observerElement) => {
        console.log(isIntersecting)
        if (isIntersecting) {
          el.src = binding.value
          stop()
        }
      }
    )
  }
})


app.mount('#app')

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
更新: 8/22/2022, 3:57:45 PM