Vue3父组件向子组件传递音频数组并实现播放的问题排查
问题分析与解决方案
核心问题点
- 父组件URL错误:音频地址里的域名部分用了逗号(
,)代替点号(.),导致地址无效,无法加载音频。 - 子组件未使用传入的Props:
onMounted里重新声明了sounds变量,完全覆盖了父组件传递的props.sounds,根本没用到外部传入的音频数组。 - 未监听Props变化:父组件修改音频列表后,子组件不会自动触发新的播放逻辑。
修正后的代码
父组件(修正URL)
<template> <div> <playsound :sounds="sounds" /> </div> </template> <script setup> import { ref, onMounted } from 'vue'; import axios from 'axios'; import playsound from './test3.vue' // 修正域名的逗号为点号,确保地址有效 const sounds = ref(['https://koh-abx.com/sound/9.mp3', 'https://koh-abx.com/sound/2.mp3']); const collection1Data = ref([]); </script>
子组件(使用Props并监听变化)
<script setup> import { ref, onMounted, watch } from 'vue'; const props = defineProps({ sounds: { type: Array, required: true } }) const audioRef = ref(null); let currentSound = 0; // 封装播放逻辑,方便复用 const playSounds = () => { // 清理之前的音频实例和事件监听,避免冲突 if (audioRef.value) { audioRef.value.pause(); audioRef.value.removeEventListener('ended', onSoundEnded); } currentSound = 0; if (props.sounds.length === 0) return; audioRef.value = new Audio(props.sounds[currentSound]); audioRef.value.addEventListener('ended', onSoundEnded); // 捕获播放错误,方便排查问题 audioRef.value.play().catch(err => console.error('音频播放失败:', err)); } // 音频播放结束后的切换逻辑 const onSoundEnded = () => { currentSound++; if (currentSound < props.sounds.length) { audioRef.value.src = props.sounds[currentSound]; audioRef.value.play().catch(err => console.error('音频播放失败:', err)); } } // 组件挂载时触发播放 onMounted(() => { playSounds(); }); // 监听音频数组变化,父组件修改后自动重新播放 watch(() => props.sounds, () => { playSounds(); }, { deep: true }); </script>
关键修正说明
- 父组件修正URL标点错误,保证音频地址可访问。
- 子组件移除硬编码的
sounds数组,直接使用props.sounds,真正接收父组件传递的音频列表。 - 封装播放逻辑为函数,在组件挂载和Props变化时复用。
- 添加
watch监听Props变化,实现父组件修改音频后子组件自动重新播放。 - 增加音频播放错误捕获,便于排查加载或播放失败的问题。
内容的提问来源于stack exchange,提问作者mrtmg
相关产品推荐
相关产品推荐

