vue实现alert
使用 window.alert 直接调用浏览器原生弹窗
在 Vue 中可以直接调用浏览器原生的 alert 方法,适用于简单提示:
methods: {
showAlert() {
window.alert("这是一个原生弹窗");
}
}
缺点是无法自定义样式,且会阻塞页面交互。
通过 Vue 组件封装自定义弹窗
创建一个可复用的 Alert 组件,支持样式和交互自定义:
<template>
<div v-if="visible" class="alert-overlay">
<div class="alert-box">
<h3>{{ title }}</h3>
<p>{{ message }}</p>
<button @click="close">确定</button>
</div>
</div>
</template>
<script>
export default {
props: {
title: String,
message: String,
visible: Boolean
},
methods: {
close() {
this.$emit('close');
}
}
};
</script>
<style scoped>
.alert-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.alert-box {
background: white;
padding: 20px;
border-radius: 8px;
}
</style>
调用方式:
<Alert
title="提示"
message="操作成功"
:visible="showAlert"
@close="showAlert = false"
/>
使用第三方库(如 SweetAlert2)
安装 SweetAlert2 增强弹窗功能:
npm install sweetalert2
在 Vue 中调用:
import Swal from 'sweetalert2';
methods: {
showSweetAlert() {
Swal.fire({
title: '自定义弹窗',
text: '支持图标、按钮和异步操作',
icon: 'success',
confirmButtonText: '确定'
});
}
}
优势包括丰富的动画、图标支持和响应式设计。
通过事件总线实现全局弹窗
利用 EventBus 在任意组件触发弹窗:
// event-bus.js
import Vue from 'vue';
export const EventBus = new Vue();
// 触发组件
EventBus.$emit('show-alert', { title: '全局提示', message: '来自任何组件' });
// 接收组件(通常在根组件)
EventBus.$on('show-alert', (data) => {
this.showAlert(data);
});
适用于跨层级组件通信的场景。
结合 Vuex 管理弹窗状态
在 Vuex 中集中管理弹窗的显示/内容:
// store.js
state: {
alert: {
show: false,
options: {}
}
},
mutations: {
setAlert(state, payload) {
state.alert = payload;
}
}
// 组件中调用
this.$store.commit('setAlert', {
show: true,
options: { title: 'Vuex弹窗', message: '状态集中管理' }
});
适合中大型项目需要统一状态管理的场景。







