vue3+ts实现一个简单的音乐组件,包括播放、暂停、切换歌曲

这个组件包含了一个音频标签和三个按钮,分别用于播放、暂停和切换歌曲。在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>
相关推荐
li35741 天前
将已有 Vue 项目通过 Electron 打包为桌面客户端的完整步骤
前端·vue.js·electron
Icoolkj1 天前
VuePress 与 VitePress 深度对比:特性、差异与选型指南
前端·javascript·vue.js
excel1 天前
CNN 分层详解:卷积、池化到全连接的作用与原理
前端
excel1 天前
CNN 多层设计详解:从边缘到高级特征的逐层学习
前端
西陵1 天前
Nx带来极致的前端开发体验——任务编排
前端·javascript·架构
大前端helloworld1 天前
从初中级如何迈入中高级-其实技术只是“入门卷”
前端·面试
东风西巷1 天前
Balabolka:免费高效的文字转语音软件
前端·人工智能·学习·语音识别·软件需求
萌萌哒草头将军1 天前
10个 ES2025 新特性速览!🚀🚀🚀
前端·javascript·vue.js
半夏陌离1 天前
SQL 入门指南:排序与分页查询(ORDER BY 多字段排序、LIMIT 分页实战)
java·前端·数据库