VueLazyload 在 Vue 2 中是可以使用的,但需要注意版本兼容性和正确配置:
安装插件
首先,通过 npm 安装 vue-lazyload。为了确保与 Vue 2 兼容,需要安装特定版本:
npm install vue-lazyload@1.2.4 --save
在 Vue 2 项目中全局注册
在项目的入口文件(通常是 main.js)中引入并使用该插件。
// main.js
import Vue from 'vue'
import VueLazyload from 'vue-lazyload'// 全局注册插件
Vue.use(VueLazyload, {// 可选的配置项loading: require('@/assets/img/common/placeholder.png'), // 加载中的图片error: require('@/assets/img/common/error.png'), // 加载失败的图片// preLoad: 1.3, // 预加载比例// attempt: 1, // 尝试加载次数
})
在组件中使用 v-lazy 指令
在需要实现懒加载的图片上,使用 v-lazy 指令代替 src 属性
<template><div><!-- 正常的图片路径 --><img v-lazy="imageSrc" alt="Lazy Loaded Image" /><!-- 或者使用对象形式,可以指定 loading 和 error 图片 --><img v-lazy="imgObj" alt="Lazy Loaded Image with config" /></div>
</template><script>
export default {data() {return {imageSrc: 'https://example.com/large-image.jpg',imgObj: {src: 'https://example.com/large-image.jpg',loading: require('@/assets/img/common/loading.gif'),error: require('@/assets/img/common/error.gif'),}}}
}
</script>