VUE移動端音樂APP學習【四】:scroll組件及loading組件開發
scroll組件
製作scroll
組件,然後嵌套一個 DOM 節點,使得該節點就能夠滾動。該組件中需要引入 BetterScroll 插件。scroll.vue:
<template> <div ref="wrapper"> <slot></slot> </div> </template> <script> import BScroll from 'better-scroll'; export default { name: 'scroll', props: { probeType: { type: Number, default: 1, }, click: { type: Boolean, default: true, }, listenScroll: { type: Boolean, default: false, }, data: { type: Array, default: null, }, }, mounted() { setTimeout(() => { this._initScroll(); }, 20); }, methods: { _initScroll() { if (!this.$refs.wrapper) { // eslint-disable-next-line no-useless-return return; } this.scroll = new BScroll(this.$refs.wrapper, { probeType: this.probeType, click: this.click, }); if (this.listenScroll) { let me = this; this.scroll.on('scroll', (pos) => { me.$emit('scroll', pos); }); } }, disable() { this.scroll && this.scroll.disable(); }, enable() { this.scroll && this.scroll.enable(); }, refresh() { this.scroll && this.scroll.refresh(); }, }, watch: { data() { setTimeout(() => { this.refresh(); }, this.refreshDelay); }, }, }; </script>在
recommend
組件中引入scroll
組件:<scroll ref="scroll" class="recommend-content" :data="discList"> <div> <div class="slider-wrapper" v-if="recommends.length"> ... </div> </scroll> import Scroll from '../../base/scroll/scroll'; components: { Slider, Scroll, },
注意:在
discList
數據渲染之前,scroll
組件所包裹的 DOM 節點是沒有高度的,頁面是無法滾動的,所以需要綁定數據,當discList
數據渲染後,scroll組件監聽並調用refresh()方法才能使頁面滾動。
由於輪播圖和推薦歌單是兩個不同介面返回的數據並且非同步請求返回數據的時間點並不一致,scroll組件所監聽到的數據就會不完整,所計算的DOM高度就偏小,會導致頁面無法滾動或滾動不完整。
解決方法:
在圖片中添加loadImage
事件,當圖片載入時就重新調用scroll
組件的refresh()
方法,重新計算 DOM 的高度,輪播圖的圖片有多張,每張圖片載入後就會重新調用refresh()
方法<a :href="item.jumpurl"> <img class="needsclick" @load="loadImage" :src="item.picurl" > </a> loadImage() { if (!this.checkLoaded) { this.$refs.scroll.refresh(); this.checkLoaded = true; } },
圖片懶載入
對於圖片過多的頁面,為了加速頁面載入速度,需要將頁面內未出現的可視區域內的圖片先不載入,等到滾動到可視區的時候再去載入,也就是圖片懶載入。
圖片懶載入需要用到 vue-lazyload 插件
// main.js import VueLazyLoad from 'vue-lazyload' Vue.use(VueLazyLoad, { loading: require('common/image/default.png') }) // recommend.vue <img width="60" height="60" v-lazy="item.picUrl">效果圖:
Loading組件
loading.vue:
<template> <div class="loading"> <img src="./loading.gif" alt="" width="24" height="24"> <p class="desc">{{title}}</p> </div> </template> <script> export default { name: 'loading', props: { title: { type: String, default: '正在載入……', }, }, }; </script> <style lang="scss" scoped> .loading { width: 100%; text-align: center; .desc { line-height: 20px; font-size: $font-size-small; color: $color-text-l; } } </style>在recommend.vue中使用loading組件:
<div class="loading-container" v-show="!discList.length"> <loading></loading> </div> import Loading from '../../base/loading/loading'; components: { Slider, Scroll, Loading, },效果圖: