具体细节以及更多拓展可前往npm官网查看:

https://www.npmjs.com/package/vue-lazyload

Github了解源码:https://github.com/hilongjw/vue-lazyload

懒加载顾名思义就是懒得加载(…吧),当我们浏览网页,文档展示在电脑窗口的一部分会加载出图片,眼睛看不到的部分就不会加载。当窗口聚焦到文档,图片就会加载。这就是懒加载。此方法有效的降低了服务器的请求压力,大大提高了客户的访问速度。

那么如何实现:

对图片标签<img/>src 属性下手,src就是请求图片地址的,所以懒加载把src属性直接替换为 v-lazy 属性。

首先创建完工程后
安装vue-lazyload组件包

npm i vue-lazyload@1.2.3 -S

这里不建议用最新版,会报错,图片加载不出来(我暂时遇到的bug)

下载好后就可以在main.js配置组件注册组件

import Vue from 'vue'
import App from './App.vue'
import router from './router'
// 1.图片懒加载插件
import VueLazyload from 'vue-lazyload'

Vue.config.productionTip = false
// 2.注册插件
Vue.use(VueLazyload, {
  preLoad: 1.3,
  // 懒加载默认加载图片
  loading: 'https://img1.imgtp.com/2022/10/02/61x2dHvC.png',
  // 加载失败后加载的图片
  error: 'https://img1.imgtp.com/2022/10/02/61x2dHvC.png',
  attempt: 1
  // the default is ['scroll', 'wheel', 'mousewheel', 'resize', 'animationend', 'transitionend']
  // listenEvents: [ 'scroll' ]
})

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

注册组件里面的具体参数配置可前往官网获取:
1参数
接着就可以随意使用图片懒加载了
例如,img添加v-lazy属性,值就是图片url

<template>
  <div class="hello">
    <h3>{{ msg }}</h3>
    
    <div v-for="item in imgSrc" :key="item.id">
      <p>内容区域</p>
      <p>内容区域</p>
      <p>内容区域</p>
      <p>内容区域</p>
      <img alt="" v-lazy=item.url />
    </div>
    
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      imgSrc: [
        { id: 1, url: "https://img1.imgtp.com/2022/10/02/x2zOdyMi.png" },
        { id: 2, url: "https://img1.imgtp.com/2022/10/02/6OcEDlzP.png" },
        { id: 3, url: "https://img1.imgtp.com/2022/10/02/PCii39ly.png" },
      ],
    };
  },
};
</script>

这里我给了三张图片,用v-for遍历了出来。3G下查看效果:
效果

Logo

前往低代码交流专区

更多推荐