vue-lazyload-图片懒加载

191 阅读1分钟
使用vue-lazyload进行图片懒加载
yarn add vue-lazyload -D

##main.js引入
import VueLazyLoad from 'vue-lazyload'
Vue.use(VueLazyLoad,{ 
	preload:1,//距离页面底部的距离(百分比)
	error:require('./assets/img/error.jpg'),
	loading:require('./assets/img/loading.jpg'),
	attempt:2//(加载失败最多尝试两次)
})
//这里需要注意的是如果放在了public文件夹中,应该这样引入图片
	Vue.use(VueLazyLoad,{ 
		preload:1,//距离页面底部的距离(百分比)
		error:require('./img/error.jpg'),
		loading:require('./img/loading.jpg'),
		attempt:2//(加载失败最多尝试两次)
	})
##vue文件中使用
	<template>
		<div id="lazyload">
			<!-- img中使用图片懒加载。 v-lazy代替v-bind:src -->
                    <ul class="img">
                        <li v-for="(item,index) in imgList"> 
                            <img v-lazy="item" alt="" style="width: 768px;"> 
                        </li>
                    </ul>
	 
                    <!-- 背景图中使用图片懒加载。 v-lazy:background-image = "" -->
                    <ul class="bgImg">
                            <li v-for="(item,index) in imgList" v-lazy:background-image="item"></li>
                    </ul>
		</div>
	</template>
	<script>
	export default {
            name:'LazyLoadDemo',
            data(){
                return{
                    imgList:[
                        require('../assets/img/1.jpg'),
                        require('../assets/img/2.jpg'),
                    ],
                }
            }
	}
	</script>
	<style lang="scss" scoped>
            #lazyload{
                width: 768px;
                background-color: #fcc;
                margin: 0 auto;
                .img{
                    width: 768px;
                    background-color: #fcc;
                }
                .bgImg{
                    li{
                        width: 768px;
                        height: 522px;  
                        margin-bottom: 10px;
                        background-repeat: no-repeat;  //注意图片大小,否则可以显示不全
                        background-size: cover;
                    }
                }
            }
	</style>