種一棵樹最好的時間是十年前,其次是如今。--誰說的不重要。vue
在作表單時,咱們常常會遇到各類input輸入框,例如在設計填寫個數時,要求輸入正整數。git
若是隻是個別輸入框,那麼咱們徹底能夠檢測input的keyup事件,在該事件裏對keyup事件進行操做便可github
<input type="text" v-model="value"
@keyup="value = value.length === 1 ? value.replace(/[^1-9]/g, '') : value.replace(/\D/g, '')" />
複製代碼
若是存在大量的要求輸入正整數,那就很差玩了bash
粉墨登場!ui
首先看下最終結果:spa
<input type="text" v-model="value" v-Int/>
複製代碼
確認過的眼神,簡單到只須要添加指令 v-Int便可實現,是否是心動的感受? 設計
若是把本身經常使用的小技能都採用自定義的方式進行維護,那豈不是美滋滋。3d
用了一段時間後,發現一個,input的值被修改了,但vue裏顯示的仍是舊值(例如輸入字母時失去焦點,值居然沒有發生改變),這是個嚴重的bug呀...因而花了一上午找緣由...找到解決方法:code
import Vue from 'vue'
export default () => {
// 針對 el-input作的限制,只能輸入正整數
Vue.directive('Int', {
bind: function (el) {
const input = el.getElementsByTagName('input')[0]
input.onkeyup = function (e) {
if (input.value.length === 1) {
input.value = input.value.replace(/[^1-9]/g, '')
} else {
input.value = input.value.replace(/[^\d]/g, '')
}
trigger(input, 'input')
}
input.onblur = function (e) {
if (input.value.length === 1) {
input.value = input.value.replace(/[^1-9]/g, '')
} else {
input.value = input.value.replace(/[^\d]/g, '')
}
trigger(input, 'input')
}
}
})
}
/*********************************
** Fn: trigger
** Intro: 參考 https://github.com/vuejs/Discussion/issues/157#issuecomment-273301588
** Author: zyx
*********************************/
const trigger = (el, type) => {
const e = document.createEvent('HTMLEvents')
e.initEvent(type, true, true)
el.dispatchEvent(e)
}
複製代碼
到這裏bug已經修復了。 該bug解決方法參考自:github.com/vuejs/Discu…cdn