咱们知道,在mint-ui的组件中,有一个MessageBox,用于弹出对话框与用户进行交互的,它支持常见的三种对话框:简单的提示框alert,提示确认框confirm,用户输入对话框prompt,这三种的用法比较简单,只要参考官网的配置去设置对应的options就能够完成经常使用的需求了。可是我最近在使用prompt时,遇到了一个问题,就是用户输入时,当输入的内容不合法点击确认时,MessageBox仍会关闭,没法提供校验功能,在网上查找了若干资料无果,无奈只好本身看MessageBox的源码,而且找到了解决方法。javascript
源码的两个文件名称叫message-box.js和message-box.vue,能够在node_modules的mint-ui中查看。下面主要介绍如何在MessageBox中提供校验功能。html
<template> <div class="mint-msgbox-wrapper"> <transition name="msgbox-bounce"> <div class="mint-msgbox" v-show="value"> <div class="mint-msgbox-header" v-if="title !== ''"> <div class="mint-msgbox-title">{{ title }}</div> </div> <div class="mint-msgbox-content" v-if="message !== ''"> <div class="mint-msgbox-message" v-html="message"></div> <div class="mint-msgbox-input" v-show="showInput"> <input v-model="inputValue" :placeholder="inputPlaceholder" ref="input"> <div class="mint-msgbox-errormsg" :style="{ visibility: !!editorErrorMessage ? 'visible' : 'hidden' }"> {{ editorErrorMessage }}</div> </div> </div> <div class="mint-msgbox-btns"> <button :class="[ cancelButtonClasses ]" v-show="showCancelButton" @click="handleAction('cancel')"> {{ cancelButtonText }}</button> <button :class="[ confirmButtonClasses ]" v-show="showConfirmButton" @click="handleAction('confirm')"> {{ confirmButtonText }}</button> </div> </div> </transition> </div> </template>上面是message-box的html部分的源码,咱们能够看到,有一个class名称为mint-msgbox-errormsg的div,这里就是错误提示信息所在的位置。
默认样式在mint-ui的样式库中定义了,也能够本身在当前页面覆盖原有样式。这个div块的显示隐藏,是根据一个叫editorErrorMessage的变量决定的,那么这个变量具体是如何控制值的呢?咱们看下面的js代码。vue
validate() { if (this.$type === 'prompt') { var inputPattern = this.inputPattern; if (inputPattern && !inputPattern.test(this.inputValue || '')) { this.editorErrorMessage = this.inputErrorMessage || '输入的数据不合法!'; this.$refs.input.classList.add('invalid'); return false; } var inputValidator = this.inputValidator; if (typeof inputValidator === 'function') { var validateResult = inputValidator(this.inputValue); if (validateResult === false) { this.editorErrorMessage = this.inputErrorMessage || '输入的数据不合法!'; this.$refs.input.classList.add('invalid'); return false; } if (typeof validateResult === 'string') { this.editorErrorMessage = validateResult; return false; } } } this.editorErrorMessage = ''; this.$refs.input.classList.remove('invalid'); return true; },
3.代码示例:java
MessageBox.prompt('请输入密码', { inputValidator: (val) => { if (val === null) { return true;//初始化的值为null,不作处理的话,刚打开MessageBox就会校验出错,影响用户体验 } return !(val.length < 6 || val.length > 8) }, inputErrorMessage: '密码长度必须在6~8位' }).then((val) => { console.info('confirm,value is' + val.value) }, () => { console.info('cancel') })4.结果预览:
上述代码请参考:https://github.com/JerryYuanJ/a-vue-app-template/blob/master/src/pages/tool/OtherTest.vuenode
若是你以为对你有帮助,欢迎star ~ git