vue慕课网音乐项目手记:54-播放控件的点击播放的实现

给当前播放的歌曲添加一个class
 <i class="current" :class="getActivatyCls(item)"></i>
getActivatyCls (item) {
      if (this.currentSong.id === item.id) {
        return 'icon-play'
      }
    },
添加点击事件:
<li class="item" v-for="(item, index) of sequenceList" :key="item.id" @click="selectItem(item, index)">
selectItem (item, index) {
      if (this.mode === playMode.random) {
        // 如果当前模式是随机播放
        index = this.playList.findIndex((song) => {
          return song.id === item.id
          // 就找到当前点击的歌曲所对应的item索引
        })
      }
      this.setCurrentIndex(index)
      this.playing(true)
    },

scrollToCurrent的实现:

scrollToCurrent (current) {
      const index = this.sequenceList.findIndex((song) => {
        return current.id === song.id
        // 找到current在song里面的位置
      })
      this.$refs.listContent.scrollToElement(this.$refs.listItem[index], 300)
    },

然后监控currentSong的变换,如果发生变化,就调用scrollToCurrent的方法:

watch: {
    currentSong (newSong, oldSong) {
      if (!this.showFlag || newSong === oldSong) {
        return
      }
      this.scrollToCurrent(newSong)
    }
  },

同时在show的时候,也要调用这个方法:

show () {
      this.showFlag = true
      setTimeout(() => {
        this.$refs.listContent.refresh()
        this.scrollToCurrent(this.currentSong)
      })
    },

这样就实现了。

发布了169 篇原创文章 · 获赞 34 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/weixin_40814356/article/details/80506933