1. <template>
    2. <div>
    3. <div v-for="item,index in data" :key="item.id">
    4. <img :data-img="item.img" :data-key="index" :data-lazy-img-list="index" />
    5. </div>
    6. </div>
    7. </template>
    8. <script setup lang="ts">
    9. import { nextTick ,onMounted} from 'vue';
    10. const data=[{
    11. img: 'https://news.sznews.com/pic/2021-03/09/e37326cc-4583-48f3-aa00-ecc2392d319d.jpg',
    12. title: '36分钟,深圳平均通勤时间出炉!GDP10强城市中仅输杭州',
    13. evaluate: (Math.random() * 10).toFixed(2),
    14. collection: (Math.random() * 100).toFixed(2),
    15. price: (Math.random() * 10).toFixed(2),
    16. monSales: (Math.random() * 20).toFixed(2),
    17. id: 1,
    18. loading: true,
    19. }]
    20. const lazyImg = (el: any, arr: any) => {
    21. const io = new IntersectionObserver((res) => {
    22. res.forEach((v: any) => {
    23. if (v.isIntersecting) {
    24. const { img, key } = v.target.dataset;
    25. v.target.src = img;
    26. v.target.onload = () => {
    27. io.unobserve(v.target);
    28. arr[key]['loading'] = false;
    29. };
    30. }
    31. });
    32. });
    33. nextTick(() => {
    34. document.querySelectorAll(el).forEach((img) => io.observe(img));
    35. });
    36. };
    37. onMounted(() => {
    38. lazyImg('[data-lazy-img-list]',data)
    39. })
    40. </script>
    41. <style scoped></style>