既然我们已经能从mock服务器拿到mock数据,现在的任务就是用拿到的数据进行页面渲染,另外,由于页面的图片数据太多,为了提高性能,我们会使用图片懒加载。本篇我们主要进行如下工作:
step1 引入图片资源 大家需要把resources中的图片资源copy到static文件夹下。
step2 将数据绑定到对应位置 对GoodsList.vue进行如下改动
<div class="accessory-list-wrap">
<div class="accessory-list col-4">
<ul>
<li v-for="item in prdList" :key="item.productId">
<div class="pic">
<a href="#"><img :src="`../../../static/${item.productImage}`" alt=""></a>
</div>
<div class="main">
<div class="name">{{item.productName}}</div>
<div class="price">{{item.salePrice}}</div>
<div class="btn-area">
<a href="javascript:;" class="btn btn--m">加入购物车</a>
</div>
</div>
</li>
</ul>
</div>
</div>
如图所示:
这里使用v-for会要求我们绑定key,这里建议用productId绑定key,原因可以看Vue 2.0 v-for 响应式key, index及item.id参数对v-bind:key值造成差异研究。
由于产品列表页面有众多的图片,影响了首屏加载速度,所以我们对图片进行懒加载。这里使用一个插件叫做vue-lazyload。
我们先安装该插件:
npm install --save vue-lazyload
然后在main.js中作如下修改:
import Vue from 'vue'
import App from './App'
import router from './router'
import VueLazyLoad from 'vue-lazyload'
import './assets/css/base.css'
import './assets/css/login.css'
import './assets/css/product.css'
Vue.config.productionTip = false
Vue.use(VueLazyLoad, {
loading: '../static/loading/loading-bars.svg',
error: '../static/ok-2.png'
})
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
在GoosList.vue中作如下修改:
<a href="#"><img v-lazy="`../../../static/${item.productImage}`" alt=""></a>
现在我们来看一下效果:
可以看到在页面滚动之前,4.jpg和5.jpg并没有下载,直到视图滚动到其可见时才开始加载。
这节主要是讲了两个小的优化点。我们提交以下代码:
git status
git diff
git add .
git commit -am 'data bind and vue-lazyload'
git push