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>
相关推荐
去伪存真3 分钟前
看我如何破解api接口文档定义空白, 还不想手动写接口TS类型定义的困局
前端·typescript
skyWang41624 分钟前
Vite模块联邦(vite-plugin-federation)实现去中心化微前端后台管理系统架构
前端
喝拿铁写前端26 分钟前
你以为你是中级前端,其实你还停留在执行阶段-完整前端成长之路
前端
前端卧龙人32 分钟前
uniapp开发技巧:开启代理与gzip优化实践
前端
hepherd32 分钟前
Vue学习笔记 - 插件
前端·vue.js
027西瓜皮33 分钟前
使用 Leaflet.js 生成北京地铁地图(Trae实现)
前端·trae
就是我33 分钟前
3种必须知道的JavaScript异步编程模型
前端·javascript·面试
青花雅月35 分钟前
写好代码之MVVC架构模式
前端·javascript·代码规范
Huanzhi_Lin38 分钟前
webpack配置导致浏览器自动刷新
前端·javascript·webpack
原生高钙39 分钟前
万字webpack精华总结:那些面试官提问的实现原理你答上来了吗
前端·webpack