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>
相关推荐
前端摸鱼匠几秒前
Vue 3 的watch监听多个数据源:讲解如何同时监听多个响应式数据的变化
前端·javascript·vue.js·前端框架·ecmascript
文心快码BaiduComate3 分钟前
用Spec给AI Agent立规矩,AI编码告别手忙脚乱
前端·后端·前端框架
东北小狐狸-Hellxz4 分钟前
后端生成的URL中含base64参数值,经tomcat重定向后偶发前端无法解密报错
java·前端·tomcat
hssfscv13 分钟前
Javeweb学习笔记——Vue+Ajax
vue.js·笔记·学习·ajax
在等星星呐17 分钟前
人工智能从0基础到精通
前端·人工智能·python
前端不太难25 分钟前
Navigation State 与页面内存泄漏的隐性关系
前端·ui·react
C+++Python31 分钟前
如何选择合适的锁机制来提高 Java 程序的性能?
java·前端·python
IT_陈寒38 分钟前
JavaScript 性能优化:7 个 V8 引擎偏爱的编码模式让你提速 40%
前端·人工智能·后端
小oo呆1 小时前
【自然语言处理与大模型】LangChainV1.0入门指南:核心组件Messages
前端·javascript·easyui
果壳~1 小时前
【前端】【canvas】图片颜色填充工具实现详解
前端