模拟系统的消息提示框而实现的一套模态对话框组件,用于消息提示、确认消息和提交内容。
从场景上说,MessageBox 的作用是美化系统自带的 alert
、confirm
和 prompt
,因此适合展示较为简单的内容。如果需要弹出较为复杂的内容,请使用 Dialog。
1、消息提示
当用户进行操作时会被触发,该对话框中断用户操作,直到用户确认知晓后才可关闭。
调用$alert
方法即可打开消息提示,它模拟了系统的 alert。
此例中接收了两个参数,message
和title
。值得一提的是,窗口被关闭后,它默认会返回一个Promise
对象便于进行后续操作的处理
<el-button type="text" @click="open">点击打开 Message Box</el-button>
<script>
export default {
methods: {
open() {
this.$alert('这是一段内容', '标题名称', {
confirmButtonText: '确定',
callback: action => {
this.$message({
type: 'info',
message: `action: ${ action }`
});
}
});
}
}
}
</script>
2、确认消息
提示用户确认其已经触发的动作,并询问是否进行此操作时会用到此对话框。
调用$confirm
方法即可打开消息提示,它模拟了系统的 confirm
。Message Box 组件也拥有极高的定制性,我们可以传入options
作为第三个参数,它是一个字面量对象。type
字段表明消息类型,可以为success
,error
,info
和warning
,无效的设置将会被忽略。注意,第二个参数title
必须定义为String
类型,如果是Object
,会被理解为options
。在这里我们用了 Promise 来处理后续响应。
<el-button type="text" @click="open2">点击打开 Message Box</el-button>
<script>
export default {
methods: {
open2() {
this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$message({
type: 'success',
message: '删除成功!'
});
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
}
}
}
</script>
将 center
设置为 true
即可开启居中布局
3、提交内容
当用户进行操作时会被触发,中断用户操作,提示用户进行输入的对话框。
调用$prompt
方法即可打开消息提示,它模拟了系统的 prompt
。可以用inputPattern
字段自己规定匹配模式,或者用inputValidator
规定校验函数,可以返回Boolean
或String
,返回false
或字符串时均表示校验未通过,同时返回的字符串相当于定义了inputErrorMessage
字段。此外,可以用inputPlaceholder
字段来定义输入框的占位符。
<script>
export default {
methods: {
open3() {
this.$prompt('请输入邮箱', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
inputErrorMessage: '邮箱格式不正确'
}).then(({ value }) => {
this.$message({
type: 'success',
message: '你的邮箱是: ' + value
});
}).catch(() => {
this.$message({
type: 'info',
message: '取消输入'
});
});
}
}
}
</script>