vue 实现 confirm
Vue 实现确认弹窗(Confirm)的方法
在 Vue 中实现确认弹窗可以通过多种方式,以下是几种常见的方法:
使用浏览器原生 confirm
最简单的方式是直接调用浏览器的原生 confirm 方法:
methods: {
handleAction() {
if (confirm('确定要执行此操作吗?')) {
// 用户点击确定
this.performAction();
} else {
// 用户点击取消
console.log('操作已取消');
}
}
}
使用第三方 UI 库
大多数流行的 Vue UI 组件库都提供了更美观的确认对话框:
Element UI
this.$confirm('确定要删除吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 确定操作
}).catch(() => {
// 取消操作
});
Ant Design Vue
this.$confirm({
title: '确认删除',
content: '确定要删除此项吗?',
onOk() {
// 确定操作
},
onCancel() {
// 取消操作
}
});
自定义 Confirm 组件
可以创建一个可复用的 Confirm 组件:
<!-- Confirm.vue -->
<template>
<div v-if="visible" class="confirm-modal">
<div class="confirm-content">
<p>{{ message }}</p>
<button @click="handleConfirm">确定</button>
<button @click="handleCancel">取消</button>
</div>
</div>
</template>
<script>
export default {
props: ['message', 'visible'],
methods: {
handleConfirm() {
this.$emit('confirm');
this.$emit('update:visible', false);
},
handleCancel() {
this.$emit('cancel');
this.$emit('update:visible', false);
}
}
}
</script>
使用方式:
<template>
<div>
<button @click="showConfirm = true">删除</button>
<Confirm
v-model="showConfirm"
message="确定要删除吗?"
@confirm="deleteItem"
@cancel="cancelDelete"
/>
</div>
</template>
使用 Vue 插件方式
可以创建一个全局的 Confirm 插件,通过 this.$confirm 调用:
// confirm-plugin.js
import Vue from 'vue';
import ConfirmComponent from './Confirm.vue';
const Confirm = {
install(Vue) {
const ConfirmConstructor = Vue.extend(ConfirmComponent);
let confirmInstance;
Vue.prototype.$confirm = (message) => {
return new Promise((resolve) => {
if (!confirmInstance) {
confirmInstance = new ConfirmConstructor({
el: document.createElement('div')
});
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);
使用 Promise 封装
可以封装一个返回 Promise 的 confirm 函数:

function confirm(message) {
return new Promise((resolve) => {
const wrapper = document.createElement('div');
wrapper.innerHTML = `
<div class="confirm-overlay">
<div class="confirm-box">
<p>${message}</p>
<button class="confirm">确定</button>
<button class="cancel">取消</button>
</div>
</div>
`;
document.body.appendChild(wrapper);
wrapper.querySelector('.confirm').addEventListener('click', () => {
document.body.removeChild(wrapper);
resolve(true);
});
wrapper.querySelector('.cancel').addEventListener('click', () => {
document.body.removeChild(wrapper);
resolve(false);
});
});
}
// 使用
async function handleAction() {
const result = await confirm('确定要执行此操作吗?');
if (result) {
// 执行操作
}
}
以上方法可以根据项目需求选择适合的实现方式,第三方 UI 库通常提供了最完整的解决方案,而自定义组件则提供了最大的灵活性。






