vue慕课网音乐项目手记:46-搜索页面跳转单曲页面

这里的逻辑比较复杂,因为需要同时改变三个state数据

  • playlist
  • sequencelist
  • currentIndex

而且,如果playlist和sequencelist里面有,还要删除之前的歌曲。

因为要同时改变多个state,所以需要用actions

export const insertSong = function ({commit, state}, song) {
  let playlist = state.playList.slice()
  let sequencelist = state.sequenceList.slice()
  let currentIndex = state.currentIndex
  // 以上用来获取数据
  let currentSong = playlist[currentIndex]
  // 记录当前歌曲
  let fpIndex = findIndex(playlist, song)
  // 查找当前list里面有没有song
  currentIndex++
  // 因为是插入歌曲,所以索引++
  playlist.splice(currentIndex, 0, song)
  // 在playlist的current+1的地方插入song
  // 做判断,如果有的话,就要删除之前的。
  if (fpIndex > -1) {
    if (currentIndex > fpIndex) {
      playlist.splice(fpIndex, 1)
      currentIndex--
    } else {
      playlist.splice(fpIndex + 1, 1)
    }
  }

  // 下面修改sequenceList
  let currentSIndex = findIndex(sequencelist, currentSong) + 1
  // 上面是查找当前的歌曲有在sequence的索引
  let fsIndex = findIndex(sequencelist, song)
  // 上面查找有没有要插入的歌曲
  sequencelist.splice(currentSIndex, 0, song)
  // 上面在sequencelist里里面去插入song这首歌曲
  if (fsIndex > -1) {
    if (currentSIndex > fsIndex) {
      sequencelist.splice(fsIndex, 1)
      // 这里不需要去currentSIndex,因为这里只用用来计算song应该插入在sequence的位置,它并不在state里面
    } else {
      sequencelist.splice(fsIndex + 1, 1)
    }
  }

  // 然后提交commit
  commit(types.SET_PLAYLIST, playlist)
  commit(types.SET_SEQUENCE_LIST, sequencelist)
  commit(types.SET_CURRENT_INDEX, currentIndex)
  commit(types.SET_FULLSCREEN, true)
  commit(types.SET_PLAYING_STATE, true)
}

然后在suggest里面调用:

...mapActions([
      'insertSong'
    ])

然后在searchItem的else里面调用action:

searchItem (item) {
      // 点击事件接收item参数,通过item的type来判断。
      if (item.type === TYPE_SINGER) {
        const singer = new Singer({
          id: item.singermid,
          name: item.singername
        })
        // 这里通过singer类来创建一个singer
        this.$router.push({
          path: `/search/${singer.id}`
        })
        this.setSinger(singer)
        // 这里是通过setSinger来改变state里面的数据
      } else {
        this.insertSong(item)
      }
    }

猜你喜欢

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