vue实现声光弹窗
Vue 实现声光弹窗的方法
使用 Vue 自定义组件
创建一个独立的弹窗组件,包含声光效果。通过 v-if 或 v-show 控制弹窗显示,利用 CSS 动画实现闪光效果,通过 Audio API 播放声音。
<template>
<div class="alert-modal" v-if="show">
<div class="alert-content">
<h3>{{ title }}</h3>
<p>{{ message }}</p>
</div>
</div>
</template>
<script>
export default {
props: ['show', 'title', 'message'],
watch: {
show(newVal) {
if (newVal) {
this.playSound();
this.flashEffect();
}
}
},
methods: {
playSound() {
const audio = new Audio('notification.mp3');
audio.play();
},
flashEffect() {
const modal = document.querySelector('.alert-modal');
modal.classList.add('flash');
setTimeout(() => modal.classList.remove('flash'), 500);
}
}
};
</script>
<style>
.alert-modal {
position: fixed;
top: 20%;
left: 50%;
transform: translateX(-50%);
padding: 20px;
background: white;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
z-index: 1000;
}
.flash {
animation: flash 0.5s;
}
@keyframes flash {
0% { box-shadow: 0 0 5px 5px rgba(255, 255, 0, 0.5); }
50% { box-shadow: 0 0 20px 10px rgba(255, 255, 0, 0.8); }
100% { box-shadow: 0 0 5px 5px rgba(255, 255, 0, 0.5); }
}
</style>
使用第三方库
对于更复杂的效果,可以考虑使用专门的动画库如 GSAP 或 Animate.css 来实现更专业的声光效果。
安装 Animate.css:
npm install animate.css
在 Vue 组件中使用:
<template>
<div class="animated flash" v-if="show">
<!-- 弹窗内容 -->
</div>
</template>
<script>
import 'animate.css';
export default {
// 组件逻辑
}
</script>
浏览器通知 API
结合浏览器通知 API 实现系统级的声光提示:
methods: {
showNotification() {
if (!("Notification" in window)) {
alert("浏览器不支持通知");
return;
}
if (Notification.permission === "granted") {
this.createNotification();
} else if (Notification.permission !== "denied") {
Notification.requestPermission().then(permission => {
if (permission === "granted") {
this.createNotification();
}
});
}
},
createNotification() {
const notification = new Notification("新消息", {
body: "您有一条新消息",
icon: "/notification-icon.png"
});
// 播放声音
const audio = new Audio('/notification.mp3');
audio.play();
// 点击通知关闭
notification.onclick = () => {
window.focus();
notification.close();
};
}
}
响应式设计考虑
确保弹窗在不同设备上都能正常显示:
@media (max-width: 768px) {
.alert-modal {
width: 90%;
top: 10%;
}
}
无障碍访问
为弹窗添加适当的 ARIA 属性,确保屏幕阅读器用户可以感知:
<div class="alert-modal" v-if="show" role="alertdialog" aria-labelledby="alert-title" aria-describedby="alert-message">
<h3 id="alert-title">{{ title }}</h3>
<p id="alert-message">{{ message }}</p>
</div>






