Element: 弹框

来自CloudWiki
跳转至: 导航搜索

弹框

模拟系统的消息提示框而实现的一套模态对话框组件,用于消息提示、确认消息和提交内容。

从场景上说,MessageBox 的作用是美化系统自带的 alert、confirm 和 prompt,因此适合展示较为简单的内容。如果需要弹出较为复杂的内容,请使用 Dialog。

¶消息提示

当用户进行操作时会被触发,该对话框中断用户操作,直到用户确认知晓后才可关闭。

Vue2022082305.png

调用$alert方法即可打开消息提示,它模拟了系统的 alert,无法通过按下 ESC 或点击框外关闭。此例中接收了两个参数,message和title。值得一提的是,窗口被关闭后,它默认会返回一个Promise对象便于进行后续操作的处理。若不确定浏览器是否支持Promise,可自行引入第三方 polyfill 或像本例一样使用回调进行后续处理。

<template>

 <el-button type="text" @click="open">点击打开 Message Box</el-button>

</template>

<script>

 export default {
   methods: {
     open() {
       this.$alert('这是一段内容', '标题名称', {
         confirmButtonText: '确定',
         callback: action => {
           this.$message({
             type: 'info',
             message: `action: ${ action }`
           });
         }
       });
     }
   }
 }

</script>

确认消息

提示用户确认其已经触发的动作,并询问是否进行此操作时会用到此对话框。

Vue2022082306.png

调用$confirm方法即可打开消息提示,它模拟了系统的 confirm。Message Box 组件也拥有极高的定制性,我们可以传入options作为第三个参数,它是一个字面量对象。type字段表明消息类型,可以为success,error,info和warning,无效的设置将会被忽略。注意,第二个参数title必须定义为String类型,如果是Object,会被理解为options。在这里我们用了 Promise 来处理后续响应。

<template>
  <el-button type="text" @click="open">点击打开 Message Box</el-button>
</template>

<script>
  export default {
    methods: {
      open() {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
    }
  }
</script>

提交内容

当用户进行操作时会被触发,中断用户操作,提示用户进行输入的对话框。

Vue2022082307.png

用$prompt方法即可打开消息提示,它模拟了系统的 prompt。可以用inputPattern字段自己规定匹配模式,或者用inputValidator规定校验函数,可以返回Boolean或String,返回false或字符串时均表示校验未通过,同时返回的字符串相当于定义了inputErrorMessage字段。此外,可以用inputPlaceholder字段来定义输入框的占位符。

<template>
  <el-button type="text" @click="open">点击打开 Message Box</el-button>
</template>

<script>
  export default {
    methods: {
      open() {
        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>