vue 实现 confirm
Vue 实现 Confirm 弹窗
在 Vue 中实现 Confirm 弹窗可以通过以下几种方式:
使用第三方库
许多成熟的 UI 库如 Element UI、Ant Design Vue 等提供了现成的 Confirm 组件。
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="onCancel">{{ cancelText }}</button> <button @click="onConfirm">{{ confirmText }}</button> </div> </div> </div> </template>
- 全局注册为插件:
// confirm-plugin.js import Vue from 'vue'; import Confirm from './Confirm.vue';
const ConfirmPlugin = { install(Vue) { Vue.component('Confirm', Confirm);
Vue.prototype.$confirm = function(options) {
return new Promise(resolve => {
const ComponentClass = Vue.extend(Confirm);
const instance = new ComponentClass({
propsData: options
});
instance.$on('confirm', () => {
resolve(true);
instance.$destroy();
});
instance.$on('cancel', () => {
resolve(false);
instance.$destroy();
});
instance.$mount();
document.body.appendChild(instance.$el);
});
}
} };

Vue.use(ConfirmPlugin);
3. 使用方式:
```javascript
// 组件内使用
this.$confirm({
title: '提示',
message: '确认删除吗?'
}).then(confirmed => {
if (confirmed) {
// 执行删除操作
}
});
使用 Promise 封装
简单场景可以直接用 Promise 封装浏览器原生 confirm:
function confirm(message) {
return new Promise(resolve => {
const result = window.confirm(message);
resolve(result);
});
}
// 使用
confirm('确认删除吗?').then(result => {
if (result) {
// 确认操作
}
});
使用 Teleport(Vue 3)
Vue 3 可以使用 Teleport 实现弹窗:
<template>
<button @click="showConfirm = true">删除</button>
<Teleport to="body">
<Confirm
v-if="showConfirm"
@confirm="handleConfirm"
@cancel="showConfirm = false"
/>
</Teleport>
</template>
<script>
import { ref } from 'vue';
import Confirm from './Confirm.vue';
export default {
components: { Confirm },
setup() {
const showConfirm = ref(false);
const handleConfirm = () => {
// 执行操作
showConfirm.value = false;
};
return { showConfirm, handleConfirm };
}
}
</script>
选择哪种实现方式取决于项目需求,简单项目可以使用原生 confirm 或第三方库,需要定制化则推荐自定义组件实现。






