vue实现alert
实现自定义 Alert 组件
在 Vue 中可以通过组件化方式实现自定义 Alert 弹窗。以下是基于 Vue 3 的实现示例:
组件代码 (Alert.vue)
<template>
<div v-if="visible" class="alert-overlay">
<div class="alert-box">
<h3>{{ title }}</h3>
<p>{{ message }}</p>
<button @click="close">{{ buttonText }}</button>
</div>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: '提示'
},
message: String,
buttonText: {
type: String,
default: '确定'
}
},
data() {
return {
visible: false
}
},
methods: {
open() {
this.visible = true
},
close() {
this.visible = false
}
}
}
</script>
<style scoped>
.alert-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 999;
}
.alert-box {
background: white;
padding: 20px;
border-radius: 8px;
max-width: 400px;
width: 90%;
}
</style>
全局注册并使用
可以将 Alert 组件注册为全局组件,方便在任何地方调用:
main.js 或全局入口文件
import { createApp } from 'vue'
import App from './App.vue'
import Alert from './components/Alert.vue'
const app = createApp(App)
app.component('Alert', Alert)
app.mount('#app')
使用示例

<template>
<button @click="showAlert">显示弹窗</button>
<Alert ref="alert" title="自定义标题" message="这是一个自定义弹窗" />
</template>
<script>
export default {
methods: {
showAlert() {
this.$refs.alert.open()
}
}
}
</script>
插件式调用
更优雅的方式是通过插件形式提供全局调用方法:
alertPlugin.js
import { createApp } from 'vue'
import Alert from './Alert.vue'
export default {
install(app) {
const alertInstance = createApp(Alert).mount(document.createElement('div'))
document.body.appendChild(alertInstance.$el)
app.config.globalProperties.$alert = (options) => {
Object.assign(alertInstance, options)
alertInstance.open()
}
}
}
在 main.js 中注册插件

import { createApp } from 'vue'
import App from './App.vue'
import alertPlugin from './alertPlugin'
const app = createApp(App)
app.use(alertPlugin)
app.mount('#app')
组件中使用
export default {
methods: {
showAlert() {
this.$alert({
title: '操作提示',
message: '确认要执行此操作吗?',
buttonText: '明白了'
})
}
}
}
使用第三方库
如果需要更完整的功能,可以考虑以下流行库:
sweetalert2: 美观强大的弹窗库element-plus: 包含完整的弹窗组件vant: 移动端友好的组件库
安装示例(以 sweetalert2 为例):
npm install sweetalert2
使用方式:
import Swal from 'sweetalert2'
Swal.fire({
title: '提示',
text: '操作成功',
icon: 'success'
})






