移動端通常對于input標簽要求輸入有一些校驗,vue的指令可達到完美校驗的作用
預期效果
<input v-model="times" :data-last_value="lastTimes" v-int v-max="8" v-min="2" />
屬性data-last_value的值用來緩存用戶輸入框上一次失去焦點后輸入的值,lastTimes是初始化的變量,后續不會再隨意更改此值, v-model一定不要和data-last_value綁定同一個變量, 因為這樣就起不到記住用戶上一次輸入值,并利用該值在校驗不通過的情況下使用它
指令實現
以下3個指令可完全獨立使用
校驗整數
const util = { isNumber(str) { const num = Number(str); return Math.floor(num) === num; } }; directives: { int: { inserted: (el) => { let oldListener = el.onblur; el.onblur = (e) => { if (oldListener) { oldListener(e); } const blurValue = Number(el.value); // 用data-last_value屬性值緩存上一次的值,以便恢復 const lastValue = el.getAttribute('data-last_value'); if (!util.isNumber(blurValue)) { util.toast('請輸入數字'); el.value = lastValue; el.dispatchEvent(new Event('input')); } if (el.value === lastValue) return; // 更新上一次的值 el.setAttribute('data-last_value', el.value); } }, }, }
校驗最小值
directives: { min: { inserted: (el, binding) => { const oldListener = el.onblur; el.onblur = (e) => { if (oldListener) { oldListener(e); } const blurValue = Number(el.value); const min = binding.value; if (blurValue < min) { // util.toast替換成自己業務的toast提示彈窗 util.toast(`最小值不能小于${min}`); el.value = min; el.dispatchEvent(new Event('input')); } const lastValue = el.getAttribute('data-last_value'); if (el.value === lastValue) return; // 更新上一次的值 el.setAttribute('data-last_value', el.value); } }, }, }
校驗最大值
directives: { max: { // 指令的定義 inserted: (el, binding) => { const oldListener = el.onblur; el.onblur = (e) => { if (oldListener) { oldListener(e); } const blurValue = Number(el.value); const max = binding.value; if (blurValue > max) { util.toast(`最大值不能大于${max}`); el.value = max; el.dispatchEvent(new Event('input')); } const lastValue = el.getAttribute('data-last_value'); if (el.value === lastValue) return; // 更新上一次的值 el.setAttribute('data-last_value', el.value); } }, }, }
小小的校驗指令沒想到里面還有那么多細節~~~
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持谷谷點程序。
轉載請注明:谷谷點程序 » vue input標簽通用指令校驗的實現