vue实现歌曲切换
Vue 实现歌曲切换功能
数据准备
在 Vue 组件中定义一个歌曲列表数组,包含歌曲名称、歌手、音频文件路径等信息:
data() {
return {
songs: [
{ id: 1, title: '歌曲1', artist: '歌手1', src: '/path/to/song1.mp3' },
{ id: 2, title: '歌曲2', artist: '歌手2', src: '/path/to/song2.mp3' },
{ id: 3, title: '歌曲3', artist: '歌手3', src: '/path/to/song3.mp3' }
],
currentSongIndex: 0,
audioPlayer: null
}
}
音频播放器初始化
在 mounted 生命周期钩子中初始化音频播放器对象:
mounted() {
this.audioPlayer = new Audio(this.songs[this.currentSongIndex].src)
}
歌曲切换逻辑
实现切换到指定索引歌曲的方法:
methods: {
playSong(index) {
if (index >= 0 && index < this.songs.length) {
this.currentSongIndex = index
this.audioPlayer.src = this.songs[index].src
this.audioPlayer.play()
}
}
}
上一首/下一首功能
添加切换上一首和下一首的方法:

methods: {
prevSong() {
let newIndex = this.currentSongIndex - 1
if (newIndex < 0) newIndex = this.songs.length - 1
this.playSong(newIndex)
},
nextSong() {
let newIndex = this.currentSongIndex + 1
if (newIndex >= this.songs.length) newIndex = 0
this.playSong(newIndex)
}
}
自动播放下一首
监听音频结束事件,实现自动播放下一首:
mounted() {
this.audioPlayer.addEventListener('ended', this.nextSong)
}
模板部分
在模板中添加播放控制按钮和歌曲信息显示:

<template>
<div class="player">
<div class="song-info">
<h3>{{ songs[currentSongIndex].title }}</h3>
<p>{{ songs[currentSongIndex].artist }}</p>
</div>
<div class="controls">
<button @click="prevSong">上一首</button>
<button @click="audioPlayer.paused ? audioPlayer.play() : audioPlayer.pause()">
{{ audioPlayer.paused ? '播放' : '暂停' }}
</button>
<button @click="nextSong">下一首</button>
</div>
<div class="playlist">
<ul>
<li v-for="(song, index) in songs"
:key="song.id"
@click="playSong(index)"
:class="{ active: currentSongIndex === index }">
{{ song.title }} - {{ song.artist }}
</li>
</ul>
</div>
</div>
</template>
样式优化
添加基本样式增强用户体验:
.player {
max-width: 400px;
margin: 0 auto;
}
.song-info {
text-align: center;
margin-bottom: 20px;
}
.controls {
display: flex;
justify-content: center;
gap: 10px;
margin-bottom: 20px;
}
.playlist ul {
list-style: none;
padding: 0;
}
.playlist li {
padding: 8px;
cursor: pointer;
border-bottom: 1px solid #eee;
}
.playlist li:hover {
background-color: #f5f5f5;
}
.playlist li.active {
background-color: #e0f7fa;
font-weight: bold;
}
音量控制
可选添加音量控制功能:
methods: {
setVolume(volume) {
this.audioPlayer.volume = volume
}
}
<input type="range" min="0" max="1" step="0.1"
v-model="volume"
@input="setVolume(volume)">
进度条显示
可选添加播放进度显示:
data() {
return {
// ...
currentTime: 0,
duration: 0
}
},
mounted() {
this.audioPlayer.addEventListener('timeupdate', () => {
this.currentTime = this.audioPlayer.currentTime
this.duration = this.audioPlayer.duration
})
}
<div class="progress">
<span>{{ formatTime(currentTime) }}</span>
<input type="range" min="0" :max="duration"
v-model="currentTime"
@change="audioPlayer.currentTime = currentTime">
<span>{{ formatTime(duration) }}</span>
</div>






