vue 实现 confirm
实现 Confirm 对话框
在 Vue 中实现确认对话框可以通过多种方式,包括使用原生 JavaScript、第三方库或自定义组件。以下是几种常见方法:
使用浏览器原生 confirm
最简单的方式是调用浏览器自带的 confirm 方法,但样式不可定制且体验较差。
methods: {
handleAction() {
if (confirm('确定要执行此操作吗?')) {
// 用户点击确定
this.performAction();
}
}
}
使用第三方 UI 库
主流 UI 库如 Element UI、Ant Design Vue 等都提供了美观的确认对话框组件。

以 Element UI 为例:
this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 确认操作
}).catch(() => {
// 取消操作
});
自定义 Confirm 组件
创建可复用的自定义组件能获得最大灵活性。

- 创建 Confirm.vue 组件:
<template> <div class="confirm-modal" v-if="visible"> <div class="confirm-content"> <h3>{{ title }}</h3> <p>{{ message }}</p> <div class="confirm-buttons"> <button @click="handleConfirm">确定</button> <button @click="handleCancel">取消</button> </div> </div> </div> </template>
- 在父组件中使用:
<template> <button @click="showConfirm = true">删除</button> <Confirm v-model="showConfirm" title="确认删除" message="确定要删除此项吗?" @confirm="deleteItem" /> </template>
export default { components: { Confirm }, data() { return { showConfirm: false }; }, methods: { deleteItem() { // 执行删除操作 } } };
```使用 Promise 封装
创建更灵活的确认方法,返回 Promise 便于链式调用。
// utils/confirm.js
export function confirm(message, title = '提示') {
return new Promise((resolve) => {
const shouldDelete = window.confirm(`${title}\n${message}`);
resolve(shouldDelete);
});
}
// 在组件中使用
import { confirm } from '@/utils/confirm';
async deleteItem() {
const isConfirmed = await confirm('确定删除吗?');
if (isConfirmed) {
// 执行删除
}
}
样式优化建议
对于自定义组件,添加 CSS 过渡效果提升用户体验:
.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;
transition: opacity 0.3s ease;
}
.confirm-content {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
以上方法可根据项目需求选择使用,第三方库方案适合快速开发,自定义组件则提供最大控制权。






