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>
相关推荐
夜郎king3 小时前
湖南高考天气查询:基于 HTML5 与百度天气 API 实现页面展示
前端·html5·百度天气实践·天气信息可视化
云水一下10 小时前
TypeScript 从零基础到精通(五):高级类型与泛型
前端·javascript·typescript
counterxing10 小时前
vibe coding 之后,我更不想打字了
前端·agent·ai编程
copyer_xyf10 小时前
Python 模块与包的导入导出
前端·后端·python
研☆香10 小时前
es6新特性功能介绍(四)
前端·ecmascript·es6
微扬嘴角11 小时前
React篇1--JSX语法规则、组件、组件实例的3大特性
前端·react.js·前端框架
copyer_xyf11 小时前
Python venv 虚拟环境
前端·后端·python
无聊的老谢11 小时前
Vue 3 + TypeScript 构建大型电信运维平台的前端架构设计
前端·vue.js·typescript
xiaofeichaichai11 小时前
Map / Set / WeakMap / WeakSet
前端·javascript
李可以量化11 小时前
成交量的终极量化策略:价量共振指标完整实现(下篇)
前端·数据库·人工智能