场景
完善列表面板上的其他功能,实现单条歌曲的删除以及整个列表歌曲的清空。
删除列表歌曲
在点击删除图标时,传递当前点击歌曲,在播放列表中查找并删除,同时有关索引的变化也要考虑进去。
- wy-player-panel.componet.html
<i class="ico trush" title="删除" (click)="onDeleteSong.emit(item)"></i>
- wy-player-panel.componet.ts
@Output() onDeleteSong = new EventEmitter<Song>(); // 删除选中歌曲
ngOnChanges (changes: SimpleChanges): void {
// 监听歌单列表
if (changes.songList) {
// 更新当前歌曲索引
this.updateCurrentIndex();
}
}
// 更新当前歌曲索引
private updateCurrentIndex () {
this.currentIndex = findIndex(this.songList, this.currentSong);
}
- wy-player.component.html
<!-- 播放面板 -->
<app-wy-player-panel
(onDeleteSong)="onDeleteSong($event)"
></app-wy-player-panel>
- wy-player.component.ts
// 删除当前歌曲
onDeleteSong (song: Song) {
const songList = this.songList.slice();
const playList = this.playList.slice();
let currentIndex = this.currentIndex;
const sIndex = findIndex(songList, song);
songList.splice(sIndex, 1);
const pIndex = findIndex(playList, song);
playList.splice(pIndex, 1);
// 判断当前索引是否需要改变
if (currentIndex > pIndex || currentIndex === playList.length) {
currentIndex--;
}
// 重新赋值
this.store$.dispatch(SetSongList({ songList }));
this.store$.dispatch(SetPlayList({ playList }));
this.store$.dispatch(SetCurrentIndex({ currentIndex }));
}
当选中当前歌曲后,面板便会将当前歌曲发送给父组件,父组件通过回调,先寻找当前歌曲在播放列表和歌曲列表中寻找其索引,然后删掉。再删掉之后便会有一个索引值改变的情况: 当删除的歌曲的索引小于当前播放歌曲的索引以及删除最后一首歌的时候便会更新当前歌曲索引减一
清空列表
清空列表操作动作比较大,借助nz模态框做一个再次确认的动作
- wy-player-panel.componet.html
<div class="clear-all">
<i class="icon trush" title="清除全部" (click)="onClearSong.emit()"></i>清除全部
</div>
- wy-player-panel.component.ts
@Output() onClearSong = new EventEmitter<void>() // 清空歌曲列表
- wy-player.component.html
<!-- 播放面板 -->
<app-wy-player-panel
(onClearSong)="onClearSong()">
</app-wy-player-panel>
- wy-player.component.ts
private nzModalServer: NzModalService;
// 清空歌曲
onClearSong () {
this.nzModalServer.confirm({
nzTitle: "确认清空列表?",
nzOnOk: () => {
this.store$.dispatch(SetSongList({ songList: [] }));
this.store$.dispatch(SetPlayList({ playList: [] }));
this.store$.dispatch(SetCurrentIndex({ currentIndex: -1 }));
}
})
}
总结
目前的代码中有很多重复的提交项,可以提取成单独的类,可优化的空间还是很大的。