【音乐App】—— Vue-music 项目学习笔记:歌手页面开发
前言:以下内容均为学习慕课网高级实战课程的实践爬坑笔记。
项目github地址:https://github.com/66Web/ljq_vue_music,欢迎Star。
一、歌手页面布局与设计 |
- 需求:联系人列表形式、左右联动的滚动列表、顶部标题随列表滚动而改变
歌手列表 | 快速入口列表 |
二、歌手数据接口抓取 |
- api目录下创建singer.js——同recommend.js,依赖jsonp和一些公共参数
import jsonp from '@/common/js/jsonp' import {commonParams, options} from '@/api/config' export function getSingerList() { const url = 'https://c.y.qq.com/v8/fcg-bin/v8.fcg' const data = Object.assign({}, commonParams, { channel: 'singer', page: 'list', key: 'all_all_all', pagesize: 100, pagenum: 1, hostUin: 0, needNewCode: 0, platform: 'yqq', g_tk: 1664029744, }) return jsonp(url, data, options) }
- singer.vue —— 数据结构与需求不同:需要两层数组结构
- 第一层数组:将所有歌手以姓名开头字母Findex——ABCD顺序排列
- 第二层数组:在每一个字母歌手数组中,按顺序再将歌手进行排列
- 热门数据:简单将前十条数据取出来
三、歌手数据处理和inger类的封装 |
- 定义_normalizeSinger()方法,规范化singer数据,接收参数list,即数据singers
const HOT_NAME = '热门' const HOT_SINGER_LEN = 10 _normalizeSinger(list){ let map = { hot: { title: HOT_NAME, items: [] } } list.forEach((item, index) => { if(index < HOT_SINGER_LEN) { map.hot.items.push({ id: item.Fsinger_mid, name: item.Fsinger_name, avatar: `https://y.gtimg.cn/music/photo_new/T001R300x300M000${item.Fsinger_mid}.jpg?max_age=2592000` }) } //根据Findex作聚类 const key = item.Findex if(!map[key]) { map[key] = { title: key, items: [] } } map[key].items.push({ id: item.Fsinger_mid, name: item.Fsinger_name, avatar: `https://y.gtimg.cn/music/photo_new/T001R300x300M000${item.Fsinger_mid}.jpg?max_age=2592000` }) }) // console.log(map) }
问题:avatar需要的数据是通过id计算得到的,且重复多次,重复代码太多
- common->js目录下创建singer.js: 用面向对象的方法,构造一个Singer类
export default class Singer { constructor({id, name}) { this.id = id this.name = name this.avatar = `https://y.gtimg.cn/music/photo_new/T001R300x300M000${id}.jpg?max_age=2592000` } }
-
JavaScript constructor 属性返回对创建此对象的数组函数的引用
-
语法:object.constructor
- 引入Singer:
import Singer from '@/common/js/singer'
使用new Singer({
id: item.Fsinger_mid,
name: item.Fsinger_name
})代替前面的大段代码,减少avatar这样重复的大段代码
- 为了得到有序列表,需要处理map
let hot = [] //title是热门的歌手 let ret = [] //title是A-Z的歌手 for(let key in map){ let val = map[key] if(val.title.match(/[a-zA-Z]/)) { ret.push(val) }else if(val.title === HOT_NAME) { hot.push(val) } }
- 为ret数组进行A-Z排序
ret.sort((a, b) => { return a.title.charCodeAt(0) - b.title.charCodeAt(0) })