这个组件包含了一个音频标签和三个按钮,分别用于播放、暂停和切换歌曲。在setup函数中定义了当前播放的歌曲、播放、暂停和切换歌曲的方法。
ts
<template>
<div>
<audio ref="audioTag" :src="currentSong.url"></audio>
<button @click="play">Play</button>
<button @click="pause">Pause</button>
<button @click="nextSong">Next Song</button>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
interface Song {
name: string;
url: string;
}
export default defineComponent({
setup() {
const audioTag = ref<null | HTMLAudioElement>(null);
const songs: Song[] = [
{ name: 'Song1', url: 'http://example.com/song1.mp3' },
{ name: 'Song2', url: 'http://example.com/song2.mp3' },
];
let currentSongIndex = 0;
const play = () => {
if (audioTag.value) {
audioTag.value.play();
}
};
const pause = () => {
if (audioTag.value) {
audioTag.value.pause();
}
};
const nextSong = () => {
currentSongIndex = (currentSongIndex + 1) % songs.length;
if (audioTag.value) {
audioTag.value.src = songs[currentSongIndex].url;
audioTag.value.play();
}
};
return {
currentSong: songs[currentSongIndex],
play,
pause,
nextSong,
};
},
});
</script>
最后,在App.vue中使用这个音乐播放器组件:
ts
<template>
<div id="app">
<MusicPlayer />
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import MusicPlayer from './components/MusicPlayer.vue';
export default defineComponent({
components: {
MusicPlayer,
},
});
</script>