vue实现歌曲切换
Vue 实现歌曲切换功能
核心思路
使用 Vue 的数据绑定和事件处理机制,结合音频 API 实现歌曲切换功能。需要维护当前播放索引、播放列表和播放状态。
实现步骤
数据准备
data() {
return {
songs: [
{ id: 1, title: '歌曲1', src: '/path/to/song1.mp3' },
{ id: 2, title: '歌曲2', src: '/path/to/song2.mp3' },
{ id: 3, title: '歌曲3', src: '/path/to/song3.mp3' }
],
currentIndex: 0,
audioPlayer: null,
isPlaying: false
}
}
音频元素初始化

mounted() {
this.audioPlayer = new Audio()
this.audioPlayer.addEventListener('ended', this.nextSong)
}
歌曲切换方法
methods: {
playSong(index) {
if (index >= 0 && index < this.songs.length) {
this.currentIndex = index
this.audioPlayer.src = this.songs[index].src
this.audioPlayer.play()
this.isPlaying = true
}
},
nextSong() {
const nextIndex = (this.currentIndex + 1) % this.songs.length
this.playSong(nextIndex)
},
prevSong() {
const prevIndex = (this.currentIndex - 1 + this.songs.length) % this.songs.length
this.playSong(prevIndex)
}
}
模板示例

<template>
<div class="player">
<h3>{{ songs[currentIndex].title }}</h3>
<audio ref="audio" :src="songs[currentIndex].src"></audio>
<button @click="prevSong">上一首</button>
<button @click="isPlaying ? audioPlayer.pause() : audioPlayer.play()">
{{ isPlaying ? '暂停' : '播放' }}
</button>
<button @click="nextSong">下一首</button>
</div>
</template>
进阶功能
播放进度控制
watch: {
currentIndex(newVal) {
this.$nextTick(() => {
this.audioPlayer.currentTime = 0
})
}
}
自动播放下一首
audioPlayer.addEventListener('ended', () => {
this.nextSong()
})
随机播放实现
shufflePlay() {
const randomIndex = Math.floor(Math.random() * this.songs.length)
this.playSong(randomIndex)
}
注意事项
- 确保音频文件路径正确
- 移动端可能需要用户交互事件触发后才能播放音频
- 考虑添加加载状态处理
- 可结合 Vuex 管理全局播放状态
- 添加错误处理机制应对网络问题
这种实现方式提供了基础的歌曲切换功能,可根据实际需求扩展播放列表管理、音量控制、歌词同步等高级功能。






