vue 实现 confirm
Vue 实现 Confirm 弹窗的方法
在 Vue 中实现 Confirm 弹窗可以通过多种方式,以下是几种常见的实现方法:
使用组件方式实现
创建一个独立的 Confirm 组件,通过 props 和事件实现交互。
<!-- 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: {
visible: Boolean,
message: String
},
methods: {
handleConfirm() {
this.$emit('confirm')
this.$emit('update:visible', false)
},
handleCancel() {
this.$emit('cancel')
this.$emit('update:visible', false)
}
}
}
</script>
使用插件方式实现
将 Confirm 封装为全局插件,通过 this.$confirm 调用。
// confirmPlugin.js
import Vue from 'vue'
import Confirm from './Confirm.vue'
const ConfirmConstructor = Vue.extend(Confirm)
const confirm = (message) => {
return new Promise((resolve) => {
const instance = new ConfirmConstructor({
propsData: { message }
})
instance.$mount()
document.body.appendChild(instance.$el)
instance.$on('confirm', () => {
resolve(true)
document.body.removeChild(instance.$el)
})
instance.$on('cancel', () => {
resolve(false)
document.body.removeChild(instance.$el)
})
})
}
Vue.prototype.$confirm = confirm
使用第三方库
许多 UI 库如 Element UI、Ant Design Vue 等已经内置了 Confirm 组件。
// 使用 Element UI
this.$confirm('确认删除吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 确认操作
}).catch(() => {
// 取消操作
})
使用浏览器原生 confirm
对于简单场景可以直接使用浏览器原生 confirm。
if (confirm('确定要删除吗?')) {
// 确认操作
} else {
// 取消操作
}
样式定制
如果需要自定义样式,可以在组件中添加 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;
}
.confirm-content {
background: white;
padding: 20px;
border-radius: 4px;
}
以上方法可以根据项目需求选择使用,组件方式适合需要高度定制的场景,插件方式提供了更便捷的调用方法,第三方库则能快速集成现有解决方案。






