vue 实现确认弹框
Vue 实现确认弹框的方法
使用 Element UI 的 MessageBox
Element UI 提供了 ElMessageBox 组件,可以快速实现确认弹框功能。安装 Element UI 后,可以直接调用 confirm 方法。

import { ElMessageBox } from 'element-ui';
ElMessageBox.confirm('确定执行此操作吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
console.log('用户点击了确定');
}).catch(() => {
console.log('用户点击了取消');
});
使用自定义组件
如果需要更灵活的弹框样式或逻辑,可以创建一个自定义的确认弹框组件。

<template>
<div class="confirm-modal" v-if="visible">
<div class="modal-content">
<p>{{ message }}</p>
<button @click="handleConfirm">确定</button>
<button @click="handleCancel">取消</button>
</div>
</div>
</template>
<script>
export default {
props: {
visible: Boolean,
message: String
},
methods: {
handleConfirm() {
this.$emit('confirm');
},
handleCancel() {
this.$emit('cancel');
}
}
};
</script>
<style>
.confirm-modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-content {
background: white;
padding: 20px;
border-radius: 5px;
}
</style>
使用 Vue 插件形式
将确认弹框封装为插件,方便全局调用。
// confirm.js
import Vue from 'vue';
import ConfirmComponent from './ConfirmComponent.vue';
const Confirm = {
install(Vue) {
const ConfirmConstructor = Vue.extend(ConfirmComponent);
let confirmInstance = null;
Vue.prototype.$confirm = (message) => {
return new Promise((resolve) => {
if (!confirmInstance) {
confirmInstance = new ConfirmConstructor({
el: document.createElement('div'),
data() {
return {
visible: false,
message: ''
};
}
});
document.body.appendChild(confirmInstance.$el);
}
confirmInstance.message = message;
confirmInstance.visible = true;
confirmInstance.$on('confirm', () => {
confirmInstance.visible = false;
resolve(true);
});
confirmInstance.$on('cancel', () => {
confirmInstance.visible = false;
resolve(false);
});
});
};
}
};
Vue.use(Confirm);
使用第三方库
除了 Element UI,还可以使用其他第三方库如 Vuetify、Ant Design Vue 等,它们也提供了类似的确认弹框功能。
// Vuetify 示例
this.$vuetify.confirm('确定执行此操作吗?').then((res) => {
if (res) {
console.log('用户点击了确定');
}
});
注意事项
- 弹框的样式可以根据项目需求自定义。
- 如果使用第三方库,确保已正确安装并引入。
- 在移动端使用时,注意弹框的适配和交互体验。






