最近陷VUE這個(gè)坑出不去了帽撑,一直在更新vue的各種插件褒搔,原生都快不會(huì)寫了栗涂,但是因?yàn)槲覒兄疲吹讲寮妥卟粍?dòng)路...
廢話不多說,看走心過程:
npm安裝方法
npm install vue-lazyload
CDN安裝方法
CDN: https://unpkg.com/vue-lazyload/vue-lazyload.js
<script src="https://unpkg.com/vue-lazyload/vue-lazyload.js"></script>
main.js
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload)
// or with options 也可以直接在這里設(shè)置參數(shù)
Vue.use(VueLazyload, {
preLoad: 1.3, //預(yù)加載的寬高比
error: 'dist/error.png',//圖片加載失敗時(shí)使用的圖片源
loading: 'dist/loading.gif',//圖片加載的路徑
attempt: 1//嘗試加載次數(shù)
})
- 官方詳解:
image.png
下面提供一個(gè)簡單的demo:
html:
<template>
<div class="loadingImg">
/*ondragstart="return false" 圖片禁止拖動(dòng)*/
<img v-lazy="img"alt="" v-for="img in list" ondragstart="return false">
<div class="gototop" @click="BackToTop">
<a>回到<br>頂部</a>
</div>
</div>
</template>
js:
<script>
export default{
data(){
return{
list:[
"/static/img/2.jpg",
"/static/img/3.jpg",
"/static/img/4.jpg",
"/static/img/5.jpg",
"/static/img/6.jpg",
"/static/img/7.jpg",
"/static/img/8.jpg",
"/static/img/9.jpg",
"/static/img/10.jpg",
"/static/img/11.jpg"
]
}
},
methods:{
BackToTop(){
$('html,body').animate({ scrollTop: 0 }, 700);
},
handleScroll () {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
console.log(scrollTop)
if(scrollTop >100){
$(".gototop").fadeIn(500);
}
},
},
mounted(){
window.addEventListener('scroll', this.handleScroll)
$(".gototop").hide();
},
created(){
}
}
</script>
css:
img[lazy=loading]{
}
img[lazy=loaded]{
animation:fade 0.5s;
}
img{
transition:all 0.5s;
display: block;
width: 400px;
margin: 0 auto;
}
@keyframes fade {
0%{
opacity: 0;
}
100%{
opacity: 1;
}
}
.gototop{
width: 40px;
height: 40px;
border-radius: 5px;
border: 1px solid #ccc;
background: #f2f2f5;
position: fixed;
right: 30px;
bottom: 50px;
font-size: 12px;
cursor: pointer;
}
.gototop a{
color: #666;
line-height: 20px;
display: inline-block;
}
簡單的圖片懶加載就實(shí)現(xiàn)了斤程。
demo項(xiàng)目已上傳到github,demo包含vue-amap,vue-particle,vue-lazyload插件的簡單使用:https://github.com/JOSIE1988/VueDemo