vue elementUI之this.$confirm的使用方式
作者:*且听风吟
这篇文章主要介绍了vue elementUI之this.$confirm的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
vue elementUI之this.$confirm的使用
当进行一些操作时,有时需要弹出一些确定信息,
一般有两种形式:提示框和确认框。
通常为一个确定动操作,一个取消操作,如下:
this.$confirm(`您确定删除吗?`, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 确定操作
}).catch(() => {
// 取消操作
this.$message({
type: 'info',
message: '已取消'
})
})页面效果:

默认情况下,当用户点击取消按钮触发取消和点击关闭按钮或遮罩层、按下 ESC 键触发关闭时, Promise 的 reject 回调和 callback 回调的参数均为 ‘cancel’ (普通弹出框中的点击取消时的回调参数)。
有时候,两个按钮都需要执行触发动作,如下:
this.$confirm(`审核通过?`, '提示', {
distinguishCancelAndClose: true,
confirmButtonText: '通过',
cancelButtonText: '不通过',
type: 'warning'
}).then(() => {
console.log('确定操作')
}).catch(action => {
// 判断是 cancel (自定义的取消) 还是 close (关闭弹窗)
if (action === 'cancel') {
noPassAudit({ id: id }).then(res => {
if (res.data.code === 100) {
this.$message({ type: 'success', message: '操作成功!' })
this.getTableData()
} else {
this.$message({ type: 'error', message: res.data.msg })
this.getTableData()
}
})
}
})页面效果:

如果将 distinguishCancelAndClose 属性设置为 true ,则当用户点击取消按钮触发取消和点击关闭按钮或遮罩层、按下 ESC 键触发关闭时,两种行为的参数分别为 ‘cancel’ 和 ‘close’ ,这样就可以在 catch 中拿到回调参数 action 进行判断做什么操作了。
注意:如果没有设置 distinguishCancelAndClose 为 true ,则两种行为都默认为取消。
Vue TypeError: this.$confirm is not a function
错误
在使用element ui,采用局部引入时候,
报错 TypeError: this.$confirm is not a function

因为没有在vue的实例上挂载confirm和message导致的报错
解决方案
修改element.js文件:
1 引入messageBox 插件
import {MessageBox} from ‘element-ui'2 在vue 的原型对象上挂载confirm
Vue.prototype.$confirm = MessageBox.confirm
如下图所示:

以后就可以放心的在vue中的任何文件使用this.confirm或者this.message了。
比如:你想用MessageBox中的confirm方法,现在可以这样用:
<template>
<div>
<el-button type="text" @click="dialogVisible = true">点击打开 Dialog</el-button>
<el-dialog
title="提示"
:visible.sync="dialogVisible"
width="30%"
:before-close="handleClose">
<span>这是一段信息</span>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
data () {
return {
dialogVisible: false
}
},
methods: {
handleClose (done) {
const _this = this
_this.$confirm('确认关闭?')
.then(_ => {
done()
})
.catch(_ => {
})
}
}
}
</script>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
