VUE移动端音乐APP学习【十八】:排行榜首页开发
前面的推荐和歌手页面已经开发完了,接下来就是排行榜首页开发
排行榜首页的基础样式如下:
<template> <div class="rank"> <div class="toplist"> <ul> <li class="item"> <div class="icon"> <img width="100" height="100" /> </div> <ul class="songlist"> <li class="song"> <span></span> <span></span> </li> </ul> </li> </ul> </div> </div> </template> <script> export default { name: 'rank', }; </script> <style lang="scss" scoped> .rank { position: fixed; width: 100%; top: 88px; bottom: 0; .toplist { height: 100%; overflow: hidden; .item { display: flex; margin: 0 20px; padding-top: 20px; height: 100px; &:last-child { padding-bottom: 20px; } .icon { flex: 0 0 100px; width: 100px; height: 100px; } .songlist { flex: 1; display: flex; flex-direction: column; justify-content: center; padding: 0 20px; height: 100px; overflow: hidden; background: $color-highlight-background; color: $color-text-d; font-size: $font-size-small; .song { @include no-wrap(); line-height: 26px; } } .loading-container { position: absolute; width: 100%; top: 50%; transform: translateY(-50%); } } } } </style>
运行后可以看到排行榜页面大致是这样的页面结构:
下面就是抓取数据
- 在api文件夹下创建rank.js 定义连接接口方法
import axios from 'axios'; export function getTopList() { return axios.get('/api/toplist'); }
- 在rank.vue中使用该方法获取接口数据
created() { this._getTopList(); }, methods: { _getTopList() { getTopList().then((res) => { console.log(res); if (res.data.code === ERR_OK) { console.log(res.data.list); } }); }, },
获取到的数据如下:
接下来就是将这些数据映射到dom上
- 首先在data()里面定义一个变量topList
data() { return { topList: [], }; },
- 将获取到的数据赋值给变量topList
_getTopList() { getTopList().then((res) => { if (res.data.code === ERR_OK) { this.topList = res.data.list; } }); },
- 在dom上遍历topList
<div class="rank"> <div class="toplist"> <ul> <li class="item" v-for="(item,index) in topList" :key="index"> <div class="icon"> <img width="100" height="100" v-lazy="item.coverImgUrl" /> </div> <ul class="songlist"> <li class="song"> <h1>{{item.name}}</h1> <span>{{item.description}}</span> </li> </ul> </li> </ul> </div> </div>
- 效果图
引入scroll组件,父元素要应用scroll组件才能进行滚动
<scroll :data="topList" class="toplist"> ... </scroll> import Scroll from '../../base/scroll/scroll'; components: { Scroll, },
因为是异步获取的数据所以要加一个loading的状态
<div class="loading-container" v-show="!topList.length"> <loading></loading> </div> import Loading from '../../base/loading/loading'; components: { Scroll, Loading, },
还需要优化一个地方:当底部有迷你播放器出现占位的时候,就需要处理一下底部的高度。
解决方法:用之前写过的playlistMixin解决这个问题。
- 引入playlistMixin
import { playlistMixin } from '../../common/js/mixin';
mixins: [playlistMixin],
- 给需要修改的dom元素加上引用
<div class="rank" ref="rank"> <scroll :data="topList" class="toplist" ref="toplist">
- 在methods里重新定义handlePlaylist(playlist) 方法
handlePlaylist(playlist) { const bottom = playlist.length > 0 ? '60px' : ''; this.$refs.rank.style.bottom = bottom; // 调用refresh()让scroll重新计算高度 this.$refs.toplist.refresh(); },
- 效果图