1.安装插件 npm install vue-lazyload
2.在入口文件main.js中引入并使用,可以配合使用图片裁剪
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 2,
error: TRANSPARENT_IMG,
loading: '',
attempt: 3,
filter: {
imgFormat(img) {
// 过滤 http(s)
const imgSrc = img.src && img.src.replace(/^https?:/, '');
if (imgSrc && (img.el.dataset.width || img.el.dataset.rule)) {
img.src = formateImg(imgSrc, img.el.dataset.width, img.el.dataset.height, img.el.dataset.mark, img.el.dataset.rule);
} else {
img.src = imgSrc;
}
},
},
});
3.修改图片加载方式为懒加载,将src属性改为v-lazy即可
图片
<img v-lazy="'/static/img/' + item.productImage" :key="'/static/img/' + item.productImage"> //:key是为了防止刷新页面或图片更改时图片不更新
背景图
<div style="width:100px;height:100px;" v-lazy:background-image="{src: item.imgpath}"></div>
v-html
<div v-html="detailData2"
v-lazy-container="{
selector: 'img',
loading: '//.x.autohome.com.cn/lyhd/public/img/autohome_detault.png',
error: '//.x.autohome.com.cn/lyhd/public/img/autohome_detault.png',
preLoad: 1.3
}">
</div>