手把手教你10分鐘做一個單頁面音樂播放器
一.話不多,先看效果:
視頻B站效果演示地址~
https://www.bilibili.com/video/BV12y4y1g71S
這是個單頁面音樂播放器,只用到了 html+css 與很基礎的vue語法,所以適合初學者,看一看10分鐘就會了~
二.詳細制作步驟(完整代碼在最后):
標簽里的vue語法解釋(先看后面的js部分再看這里更好理解):
給這個標簽 v-model='query’雙向綁定數據query,@keyup.enter="searchMusic"綁定鍵盤回車事件,觸發searMusic函數。
{{item.name}}
放內容,寫在{{}}里。item相對于變量。
v-for="" 根據 musicList這個數組里元素的數量,動態生成多少個 li 。
@click="playMusic(item.id)點擊事件,觸發playMusic(item.id)函數,并傳參數。
:class="{playing:isPlay},若isPlay值為真,playing這個選擇器生效。
歌曲主要調用的是網易云的公開API所得~
new Vue({ el:"#container", data(){ return{ //搜索關鍵字 query:'', //歌曲列表 musicList:[], //當前歌曲地址 url:'', //海報地址 poster:'./img/timg4.jpg', //判斷是否正在播放 isPlay: false, //評論 comment:[] } }, methods:{ searchMusic(){ // 判斷搜索框有沒有字 if(this.query==''){ //沒有自己返回 return; } // 發送請求獲得數據 axios({ url:'https://autumnfish.cn/search', method:'get', params:{ keywords:this.query } }).then(res=>{ //把獲取數據傳給musicList數組,可以通過 console.log(res);查看自己想要的數據 this.musicList = res.data.result.songs; }) }, playMusic(id){ //獲得歌曲的url axios({ url:'https://autumnfish.cn/song/url', method:'get', params:{ id:id } }).then(res=>{ // 將當前歌曲地址設置為這個 this.url = res.data.data[0].url; }) //獲取歌曲海豹 axios({ url:'https://autumnfish.cn/song/detail', method:'get', params:{ ids:id } }).then(res=>{ // 把圖片地址純存在poster數組 this.poster=res.data.songs[0].al.picUrl }) //獲取評論 axios({ url:'https://autumnfish.cn/comment/hot', method:'get', params:{ type:0, id:id } }).then(res=>{ // 把評論的數據存在comment數組,包括頭像,網名等等,可以通過 console.log(res);查看自己想要的數據 this.comment=res.data.hotComments }) }, // 歌曲是正在播放觸發 play(){ this.isPlay = true; }, // 歌曲是停止觸發 pause(){ this.isPlay = false; } } })
三. 完整代碼(需要素材與源文件的私信或在評論區留下郵箱,我發你呀):
{{item.user.nickname}}
{{item.content}}