[Angular实战网易云]——17、删除和清空歌曲

本文介绍了在Angular应用中实现歌曲列表的删除和清空功能。删除操作涉及查找歌曲索引并更新,而清空列表则通过模态框进行二次确认。文章总结指出代码可优化空间较大。
摘要由CSDN通过智能技术生成

场景

完善列表面板上的其他功能,实现单条歌曲的删除以及整个列表歌曲的清空。


删除列表歌曲

在点击删除图标时,传递当前点击歌曲,在播放列表中查找并删除,同时有关索引的变化也要考虑进去。

  • 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 }));
            }
        })
    }


总结

目前的代码中有很多重复的提交项,可以提取成单独的类,可优化的空间还是很大的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值