vue实现声光弹窗
Vue 实现声光弹窗的方法
基础弹窗组件
创建基础弹窗组件 AlertModal.vue,包含动画和样式:
<template>
<transition name="fade">
<div v-if="show" class="alert-modal" :class="{'flash': isFlashing}">
<div class="modal-content">
<slot></slot>
</div>
</div>
</transition>
</template>
<script>
export default {
props: {
show: Boolean,
flash: Boolean
},
computed: {
isFlashing() {
return this.flash
}
}
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
.alert-modal {
position: fixed;
top: 20%;
left: 50%;
transform: translateX(-50%);
padding: 20px;
background: #ff4757;
color: white;
border-radius: 8px;
box-shadow: 0 0 20px rgba(255, 71, 87, 0.7);
z-index: 1000;
}
.flash {
animation: flash 0.5s infinite alternate;
}
@keyframes flash {
from { box-shadow: 0 0 10px rgba(255, 71, 87, 0.7); }
to { box-shadow: 0 0 30px rgba(255, 71, 87, 1); }
}
</style>
声音控制逻辑
在调用弹窗时加入声音效果:

// 在工具文件中定义声音播放方法
export function playAlertSound() {
const audio = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3')
audio.volume = 0.3
audio.play().catch(e => console.log('Audio play failed:', e))
}
组合使用
在父组件中使用弹窗和声音:
<template>
<button @click="triggerAlert">触发警报</button>
<AlertModal :show="showAlert" :flash="true">
警告!发现异常情况!
</AlertModal>
</template>
<script>
import AlertModal from './AlertModal.vue'
import { playAlertSound } from './alertUtils'
export default {
components: { AlertModal },
data() {
return {
showAlert: false
}
},
methods: {
triggerAlert() {
this.showAlert = true
playAlertSound()
setTimeout(() => {
this.showAlert = false
}, 3000)
}
}
}
</script>
增强效果选项
-
震动反馈(需要用户授权):

function triggerVibration() { if ('vibrate' in navigator) { navigator.vibrate([200, 100, 200]) } } -
自定义音效:
const soundMap = { warning: 'warning-sound.mp3', success: 'success-sound.mp3' }
export function playCustomSound(type) { const audio = new Audio(soundMap[type]) audio.play() }
#### 无障碍支持
为弹窗添加ARIA属性:
```vue
<div class="alert-modal" role="alert" aria-live="assertive">
<!-- 内容 -->
</div>






