Vue2移动端网易云项目

发布于:2022-10-21 ⋅ 阅读:(421) ⋅ 点赞:(0)

项目下载地址

成品图

 

 

 

 

1 运行网易云本地接口

 创建脚手架引入包

vue create music
yarn add axios moment vant vue-router
yarn add babel-plugin-import postcss postcss-pxtorem@5.1.1 -D

关闭eslint

配置vant按需引入

 "plugins": [
      ["import", {
        "libraryName": "vant",
        "libraryDirectory": "es",
        "style": true
      }]
    ]

 配置postcss.config.js

module.exports = {

    plugins: {
        'postcss-pxtorem': {
            rootValue: 37.5,
            propList: ['*']
        }
    }
}

创建页面

vant官网引入组件

Vant 2 - Mobile UI Components built on Vue

配置路由:在layout页面上切换home和search

search和home为layout的子路由

 配置van-tabbar route


 

 实现头部底布名称统一切换

 

用van-row来布局页面

发请求显示在页面上

 

 

 

把列表数据封装成组件 SongItem.vue

<template>
  <van-cell :title="name" :label="author+name" @click="$router.push({path:'/comment',query:{id:id}})">
    <!-- 使用 right-icon 插槽来自定义右侧图标 -->
    <template #right-icon>
      <van-icon name="play-circle" @click="playFn" />
    </template>
  </van-cell>
</template>

<script>
export default {
  name: "SongItem",
  props:{
    name:String,
    author:String,
        id:Number
  },
  methods:{
  playFn(){
    this.$router.push({
      path:'/play',
      query:{
        id:this.id
      }
    })
  }
}}
</script>

<style scoped>

</style>

配置search页面

用到了防抖

<template>
  <div>
    <van-search v-model="SearchValue" placeholder="请输入搜索关键词" shape="round"/>
    <div class="search_wrap" v-if="this.resultList.length===0">
      <!-- 标题 -->
      <p class="hot_title">热门搜索</p>
      <!-- 热搜关键词容器 -->
      <div class="hot_name_wrap">
        <!-- 每个搜索关键词 -->
        <span v-for="(obj,index) in SearchList" :key="index" class="hot_item"
              @click="btn(obj.first)"> {{ obj.first }}</span>
      </div>
    </div>
    <!-- 搜索结果 -->
    <div class="hot_search" v-else>
      <!-- 标题 -->
      <p class="hot_title">最佳匹配</p>
      <SongItem  v-for="obj in resultList" :key="obj.id"
                 :name="obj.name"
                 :author="obj.ar[0].name +obj.name"
                 :id="obj.id"/>
    </div>
  </div>
</template>

<script>
import {hotSearchAPI, searchResultAPI} from "@/api";
import SongItem from "@/components/SongItem";
export default {
  data() {
    return {
      SearchValue: '',
      SearchList: [],
      resultList: [],
      timer: null
    };
  },
  components:{
    SongItem
  },
  async created() {
    const res = await hotSearchAPI()
    console.log(res)
    this.SearchList = res.data.result.hots
  },
  methods: {
   async btn(first) {
      this.SearchValue = first
      const res = await searchResultAPI({
        type: 1,
        keywords: this.SearchValue
      });
      this.resultList = res.data.result.songs
     setTimeout(()=>{
       clearTimeout(this.timer)
     })
    }
  },
  watch: {
    SearchValue(val) {
      clearTimeout(this.timer)
      if (val.length === 0) return this.resultList = [];
      this.timer = setTimeout(async () => {
        const res = await searchResultAPI({
          type: 1,
          keywords: this.SearchValue
        });
        this.resultList = res.data.result.songs
      }, 300)
    }
  }
};
</script>

<style scoped>
/* 搜索容器的样式 */
.search_wrap {
  padding: 0.266667rem;
}

/*热门搜索文字标题样式 */
.hot_title {
  font-size: 0.32rem;
  color: #666;
}

/* 热搜词_容器 */
.hot_name_wrap {
  margin: 0.266667rem 0;
}

/* 热搜词_样式 */
.hot_item {
  display: inline-block;
  height: 0.853333rem;
  margin-right: 0.213333rem;
  margin-bottom: 0.213333rem;
  padding: 0 0.373333rem;
  font-size: 0.373333rem;
  line-height: 0.853333rem;
  color: #333;
  border-color: #d3d4da;
  border-radius: 0.853333rem;
  border: 1px solid #d3d4da;
}

/* 给单元格设置底部边框 */
.van-cell {
  border-bottom: 1px solid lightgray;
}
</style>

配置Play页面实现音乐播放

<template>
  <div class="play">
    <!-- 模糊背景(靠样式设置), 固定定位 -->
    <div
      class="song-bg"
      :style="`background-image: url(${
        songInfo && songInfo.al && songInfo.al.picUrl
      }?imageView&thumbnail=360y360&quality=75&tostatic=0);`"
    ></div>
    <!-- 播放页头部导航 -->
    <div class="header">
      <van-icon
        name="arrow-left"
        size="20"
        class="left-incon"
        @click="$router.back()"
      />
    </div>
    <!-- 留声机 - 容器 -->
    <div class="song-wrapper">
      <!-- 留声机本身(靠css动画做旋转) -->
      <div
        class="song-turn ani"
        :style="`animation-play-state:${playState ? 'running' : 'paused'}`"
      >
        <div class="song-img">
          <!-- &&写法是为了防止报错, 有字段再继续往下访问属性 -->
          <img
            style="width: 100%"
            :src="`${
              songInfo && songInfo.al && songInfo.al.picUrl
            }?imageView&thumbnail=360y360&quality=75&tostatic=0`"
            alt=""
          />
        </div>
      </div>
      <!-- 播放按钮 -->
      <div class="start-box" @click="audioStart">
        <span class="song-start" v-show="!playState"></span>
      </div>
      <!-- 播放歌词容器 -->
      <div class="song-msg">
        <!-- 歌曲名 -->
        <h2 class="m-song-h2">
          <span class="m-song-sname"
            >{{ songInfo.name }}-{{
              songInfo && songInfo.ar && songInfo.ar[0].name
            }}</span
          >
        </h2>
        <!-- 歌词部分-随着时间切换展示一句歌词 -->
        <div class="lrcContent">
          <p class="lrc">{{ curLyric }}</p>
        </div>
      </div>
      <!-- 留声机 - 唱臂 -->
      <div class="needle" :style="`transform: rotate(${needleDeg});`"></div>
    </div>
    <!-- 播放音乐真正的标签
      看接口文档: 音乐地址需要带id去获取(但是有的歌曲可能404)
      https://binaryify.github.io/NeteaseCloudMusicApi/#/?id=%e8%8e%b7%e5%8f%96%e9%9f%b3%e4%b9%90-url
     -->
    <audio
      ref="audio"
      preload="true"
      :src="`https://music.163.com/song/media/outer/url?id=${id}.mp3`"
    ></audio>
  </div>
</template>

<script>
// 获取歌曲详情和 歌曲的歌词接口
import { getSongByIdAPI, getLyricByIdAPI } from '@/api'
import { Icon } from 'vant'
export default {
  components: {
    [Icon.name]: Icon,
  },
  name: 'play',
  data() {
    return {
      playState: false, // 音乐播放状态(true暂停, false播放)
      id: this.$route.query.id, // 上一页传过来的音乐id
      songInfo: {}, // 歌曲信息
      lyric: {}, // 歌词枚举对象(需要在js拿到歌词写代码处理后, 按照格式保存到这个对象)
      curLyric: '', // 当前显示哪句歌词
      lastLy: '' // 记录当前播放歌词
    }
  },
  computed: {
    needleDeg() { // 留声机-唱臂的位置属性
      return this.playState ? '-7deg' : '-38deg'
    }
  },
  methods: {
    async getSong() { // 获取歌曲详情, 和歌词方法
      const res = await getSongByIdAPI(this.id)
      this.songInfo = res.data.songs[0]
      // 获取-并调用_formatLyr方法, 处理歌词
      const lyrContent = await getLyricByIdAPI(this.id)
      const lyricStr = lyrContent.data.lrc.lyric
      this.lyric = this._formatLyr(lyricStr)
      // 初始化完毕先显示零秒歌词
      this.curLyric = this.lyric[0]
    },
    _formatLyr(lyricStr) {
      // 可以看network观察歌词数据是一个大字符串, 进行拆分.
      let reg = /\[.+?\]/g // 
      let timeArr = lyricStr.match(reg) // 匹配所有[]字符串以及里面的一切内容, 返回数组
      console.log(timeArr); // ["[00:00.000]", "[00:01.000]", ......]
      let contentArr = lyricStr.split(/\[.+?\]/).slice(1) // 按照[]拆分歌词字符串, 返回一个数组(下标为0位置元素不要,后面的留下所以截取)
      console.log(contentArr);
      let lyricObj = {} // 保存歌词的对象, key是秒, value是显示的歌词
      timeArr.forEach((item, index) => {
        // 拆分[00:00.000]这个格式字符串, 把分钟数字取出, 转换成秒
        let ms = item.split(':')[0].split('')[2] * 60
        // 拆分[00:00.000]这个格式字符串, 把十位的秒拿出来, 如果是0, 去拿下一位数字, 否则直接用2位的值
        let ss = item.split(':')[1].split('.')[0].split('')[0] === '0' ? item.split(':')[1].split('.')[0].split('')[1] : item.split(':')[1].split('.')[0]
        // 秒数作为key, 对应歌词作为value
        lyricObj[ms + Number(ss)] = contentArr[index]
      })
      // 返回得到的歌词对象(可以打印看看)
      console.log(lyricObj);
      return lyricObj
    },
    audioStart() { // 播放按钮 - 点击事件
      if (!this.playState) { // 如果状态为false
        this.$refs.audio.play() // 调用audio标签的内置方法play可以继续播放声音
      } else {
        this.$refs.audio.pause() // 暂停audio的播放
      }
      this.playState = !this.playState // 点击设置对立状态
    },
    showLyric() {
      // 监听播放audio进度, 切换歌词显示
      this.$refs.audio.addEventListener('timeupdate', () => {
        let curTime = Math.floor(this.$refs.audio.currentTime)
        // 避免空白出现
        if (this.lyric[curTime]) {
          this.curLyric = this.lyric[curTime]
          this.lastLy = this.curLyric
        } else {
          this.curLyric = this.lastLy
        }
      })
    }
  },
  mounted() {
    this.getSong()
    this.showLyric()
    console.log(this.$route.query.id);
  }
}
</script>

<style scoped>
.header {
  height: 50px;
}
.play {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
}
.song-bg {
  background-color: #161824;
  background-position: 50%;
  background-repeat: no-repeat;
  background-size: auto 100%;
  transform: scale(1.5);
  transform-origin: center;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  height: 100%;
  overflow: hidden;
  z-index: 1;
  opacity: 1;
  filter: blur(25px); /*模糊背景 */
}
.song-bg::before{ /*纯白色的图片做背景, 歌词白色看不到了, 在背景前加入一个黑色半透明蒙层解决 */
  content: " ";
  background: rgba(0, 0, 0, 0.5);
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom:0;
}
.song-wrapper {
  position: fixed;
  width: 247px;
  height: 247px;
  left: 50%;
  top: 50px;
  transform: translateX(-50%);
  z-index: 10001;
}
.song-turn {
  width: 100%;
  height: 100%;
  background: url("./img/bg.png") no-repeat;
  background-size: 100%;
}
.start-box {
  position: absolute;
  width: 156px;
  height: 156px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  justify-content: center;
  align-items: center;
}
.song-start {
  width: 56px;
  height: 56px;
  background: url("./img/start.png");
  background-size: 100%;
}
.needle {
  position: absolute;
  transform-origin: left top;
  background: url("./img/needle-ab.png") no-repeat;
  background-size: contain;
  width: 73px;
  height: 118px;
  top: -40px;
  left: 112px;
  transition: all 0.6s;
}
.song-img {
  width: 154px;
  height: 154px;
  position: absolute;
  left: 50%;
  top: 50%;
  overflow: hidden;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}
.m-song-h2 {
  margin-top: 20px;
  text-align: center;
  font-size: 18px;
  color: #fefefe;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.lrcContent {
  margin-top: 50px;
}
.lrc {
  font-size: 14px;
  color: #fff;
  text-align: center;
}
.left-incon {
  position: absolute;
  top: 10px;
  left: 10px;
  font-size: 24px;
  z-index: 10001;
  color: #fff;
}
.ani {
  animation: turn 5s linear infinite;
}
@keyframes turn {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}
</style>

配置comment页面

<template>
  <div>
    <van-nav-bar title="评论" fixed left-arrow @click-left="$router.back()"/>
    <div>
      <div class="main" >
        <!-- 下拉刷新 -->
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
          <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
            <van-cell v-for="(c,index) in list" :key="index">
              <div class="wrap" >
                <div class="img_wrap">
                  <img :src="c.user.avatarUrl" alt="">
                </div>
                <div class="conent_wrap">
                  <div class="header_wrap" >
                    <div class="info_wrap">
                      <p>{{c.user.nickname}}</p>
                      <p>{{c.time}}</p>
                    </div>
                    <div>{{c.likedCount}}点赞</div>
                  </div>
                  <div class="footer_wrap">
                    {{c.content}}
                  </div>

                </div>
              </div>
            </van-cell>
          </van-list>
        </van-pull-refresh>

      </div>
    </div>
  </div>
</template>
<script>
import {getCommentAPI} from "@/api";
export default {
  name:'Comment',
  data(){
    return {
      id : this.$route.query.id,
      commentsInfo:[], // 每次接收20个评论数据
      page:1, // 页码
      loading:false, // 下拉加载状态
      finished:false, // 所有数据是否加载完成状态
      refreshing:true, // 上拉加载状态
      list:[] // 所有数据
    }
  },
  methods: {
    //获取数据
    async getList(){
      const getComment = await getCommentAPI({id:this.id,type:0,limit:20,offset:(this.page -1 )*20});
      this.commentsInfo = getComment.data.hotComments;
      console.log(getComment)
      this.commentsInfo.forEach(obj=>this.list.push(obj))
      this.loading = false;
    },

    // 上拉刷新
    async onLoad(){
      console.log(this.list.length)
      if(this.loading){
        this.getList();
        this.page++;
        this.refreshing = false;
      }

      if(this.list.length %20 != 0) {
        this.loading = false;
        this.finished = true;
      }
    },

    // 下拉刷新
    async onRefresh(){
      this.finished = false;
      this.loading = true;
      this.onLoad();
    }

  },

}
</script>

<style scoped>
.main {
  padding-top: 46px;
}
.wrap {
  display: flex;
}
.img_wrap {
  width: 0.8rem;
  height: 0.8rem;
  margin-right: 0.266667rem;
}
.img_wrap img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
.conent_wrap {
  flex: 1;
}
.header_wrap {
  display: flex;
}
.info_wrap {
  flex: 1;
}
.info_wrap p:first-child {
  font-size: 0.373333rem;
  color: #666;
}
.info_wrap p:last-of-type {
  font-size: 0.24rem;
  color: #999;
}
.header_wrap div:last-of-type {
  color: #999;
  font-size: 0.293333rem;
}
.footer_wrap {
  font-size: 0.4rem;
  color: #333;
}
</style>


网站公告

今日签到

点亮在社区的每一天
去签到