咱們知道,在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