vue alert实现
使用 Vue 实现 Alert 组件
在 Vue 中实现 Alert 组件可以通过自定义组件或结合第三方库完成。以下是几种常见方法:
自定义 Alert 组件
创建一个可复用的 Alert 组件,通过 props 控制显示状态和内容:

<template>
<div v-if="show" class="alert" :class="`alert-${type}`">
{{ message }}
<button @click="close">×</button>
</div>
</template>
<script>
export default {
props: {
show: Boolean,
type: {
type: String,
default: 'info'
},
message: String
},
methods: {
close() {
this.$emit('close')
}
}
}
</script>
<style>
.alert {
padding: 10px;
margin: 10px 0;
border-radius: 4px;
}
.alert-info {
background: #d1ecf1;
color: #0c5460;
}
.alert-success {
background: #d4edda;
color: #155724;
}
</style>
使用事件总线全局调用
通过事件总线实现全局 Alert 调用:

// main.js
Vue.prototype.$eventBus = new Vue()
// Alert.vue
export default {
data() {
return {
show: false,
message: '',
type: 'info'
}
},
created() {
this.$eventBus.$on('showAlert', (payload) => {
this.show = true
this.message = payload.message
this.type = payload.type || 'info'
setTimeout(() => this.show = false, payload.duration || 3000)
})
}
}
使用第三方库
对于更复杂的需求,可以考虑以下库:
sweetalert2: 提供美观的弹窗效果vue-notification: 轻量级通知系统element-ui或vant等 UI 框架内置的 Alert 组件
使用 Composition API
在 Vue 3 中可以使用 Composition API 创建响应式 Alert:
import { ref } from 'vue'
export function useAlert() {
const alert = ref({
show: false,
message: '',
type: 'info'
})
function showAlert(message, type = 'info') {
alert.value = { show: true, message, type }
setTimeout(() => alert.value.show = false, 3000)
}
return { alert, showAlert }
}
这些方法可以根据项目需求选择或组合使用,实现灵活的消息提示功能。






