vue实现声光弹窗
Vue 实现声光弹窗的方法
基础弹窗组件
创建一个基础弹窗组件 AlertModal.vue,包含动画和样式:
<template>
<transition name="fade">
<div v-if="visible" class="alert-modal" :class="type">
<div class="content">{{ message }}</div>
</div>
</transition>
</template>
<script>
export default {
props: {
visible: Boolean,
message: String,
type: { type: String, default: 'info' } // 支持 success/warning/error 等类型
}
}
</script>
<style scoped>
.alert-modal {
position: fixed;
top: 20px;
right: 20px;
padding: 15px;
border-radius: 4px;
box-shadow: 0 0 10px rgba(0,0,0,0.2);
animation: pulse 1.5s infinite;
}
.success { background-color: #4CAF50; color: white; }
.warning { background-color: #FFC107; color: black; }
.error { background-color: #F44336; color: white; }
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
@keyframes pulse {
0% { box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.7); }
70% { box-shadow: 0 0 0 10px rgba(76, 175, 80, 0); }
100% { box-shadow: 0 0 0 0 rgba(76, 175, 80, 0); }
}
</style>
添加声音效果
在组件挂载时播放提示音:
<script>
export default {
// ...其他代码
mounted() {
const audio = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3');
audio.play().catch(e => console.log("Audio playback failed:", e));
}
}
</script>
全局调用方式
创建插件式调用方法(在 main.js 中注册):

// alertPlugin.js
const AlertPlugin = {
install(Vue) {
const AlertConstructor = Vue.extend(AlertModal)
const alertInstance = new AlertConstructor()
document.body.appendChild(alertInstance.$mount().$el)
Vue.prototype.$alert = (message, type = 'info', duration = 3000) => {
alertInstance.message = message
alertInstance.type = type
alertInstance.visible = true
setTimeout(() => {
alertInstance.visible = false
}, duration)
}
}
}
// main.js
import AlertPlugin from './alertPlugin'
Vue.use(AlertPlugin)
使用方法
在任意组件中触发:
this.$alert('操作成功!', 'success')
// 或
this.$alert('发生错误', 'error', 5000)
高级定制选项
-
添加更多动画效果:

.alert-modal { transform: translateY(-20px); transition: transform 0.3s ease-out; } .alert-modal.show { transform: translateY(0); } -
支持自定义音效:
Vue.prototype.$alert = (message, options = {}) => { if (options.sound) { new Audio(options.sound).play() } // ...其他逻辑 } -
响应式位置调整:
@media (max-width: 768px) { .alert-modal { width: 90%; left: 5%; right: auto; } }






