首先 ,在命令行輸入npm install vue-lazyload
&&cnpm install vue-lazyload
然后,在main.js里引入這個模塊。
import 'VueLazyload' from 'vue-lazyload'
Vue.use(VueLazyload,{
preload:1.3,//預(yù)加載的寬高
loading:"img的加載中的顯示的圖片的路徑",
error:"img加載失敗時現(xiàn)實的圖片的路徑",
attempt:3,//嘗試加載的次數(shù)
listenEvents:['scroll','wheel','mousewheel','resize','animationend','transitionend','touchmove'], //你想讓vue監(jiān)聽的事件
})
然后在app.vue的template里寫一個
<img v-lazy="img.src"/>
然后在app.vue的script里寫
data(){
return {
img:{
src:"圖片的真是路徑"
}
}
}
捋一下思路:
//main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import $ from 'jquery'
import 'assets/bootstrap/css/bootstrap.min.css'
import 'assets/bootstrap/js/bootstrap.min'
import router from '@/router/index'
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload,{
preload:1.3,
loading:require('../static/imgs/ad3.png'),
//解釋一下為什么是require('.....url'):因為vue自帶webpack打包工具劫扒,如果是圖片路徑就會把他當(dāng)成模塊解析州藕,所以直接引入就好了黔牵。
//記得把里面的路徑換成自己的哦
listenEvents:['mousewheel'],
})
//載入vue-router
//import Vue from 'vue'
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
//app.vue
<template>
<div id="app">
<navbar></navbar>
<router-view></router-view>
<hello></hello>
<ul>
<li v-for="item in imgUrl">
<img v-lazy="item.src" alt="" width="300" height="150"/>
</li>
</ul>
<img v-lazy='img[0].src'/>
</div>
</template>
<script>
import hello from './components/Hello'
import Navbar from '@/components/navBar'
import route from '@/components/route'
export default {
name: 'app',
components:{
hello,
Navbar
},
data() {
return {
imgUrl: [
{src: require('@/assets/imgs/ad1.png')},//記得把里面的路徑換成自己的哦
{src: require('@/assets/imgs/ad1.png')},//記得把里面的路徑換成自己的哦
],
img:[
{src:require('@/assets/imgs/ad2.png')}//記得把里面的路徑換成自己的哦
]
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>