vue實現(xiàn)input文本框只能輸入0-99的正整數(shù)問題
更新時間:2022年10月21日 14:11:06 作者:前端李小白
這篇文章主要介紹了vue實現(xiàn)input文本框只能輸入0-99的正整數(shù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
vue input文本框只能輸入0-99的正整數(shù)
利用vue里面自帶的watch監(jiān)聽器就可以了。話不多說,直接貼代碼。
? ? ? ? ? ? <div class="age-select"> ? ? ? ? ? ? <input type="text" class="fromAge-input" v-model="fromAge" />至 ? ? ? ? ? ? <input type="text" class="toAge-input" v-model="toAge" /> ? ? ? ? ? ? </div>
data里面
? ? ?data () { return{? ? ? ? fromAge: '0',? ? ? ? ?toAge: '99' ? ? ? ?}? ? ? ? ?}
在watch里面:
? ? watch: { ? ? ? ? fromAge (newName, oldName) { ? ? ? ? ? var reg = /^([1-9]\d|\d)$/ ? ? ? ? ? if (!reg.test(newName)) { ? ? ? ? ? ? this.fromAge = '' ? ? ? ? ? } else { ? ? ? ? ? ? this.fromAge = newName ? ? ? ? ? } ? ? ? ? }, ? ? ? ? toAge (newName, oldName) { ? ? ? ? ? var reg = /^([1-9]\d|\d)$/ ? ? ? ? ? if (!reg.test(newName)) { ? ? ? ? ? ? this.toAge = '' ? ? ? ? ? } else { ? ? ? ? ? ? this.toAge = newName ? ? ? ? ? } ? ? ? ? } ? ? ? },
效果如下:
這里輸入框只能輸入0-99的正整數(shù),如果不是的話就會清空掉數(shù)字。如果我們還想加入前面的數(shù)字不能大于后面的數(shù)字的話,我們只需要在需要的方法里面加一個判定條件就可以了。代碼如下:
if (this.fromAge > this.toAge) { /* 如果起始年齡大于結(jié)束年齡的話,顯示提示框 */ return this.$message.error('起始年齡不能大于結(jié)束年齡') }
效果如下:
通過自定義指令實現(xiàn)文本框只能輸入正整數(shù)
directives: { numInput(el) { el.addEventListener("keypress", function (e) { e = e || window.event; let charcode = typeof e.charCode === "number" ? e.charCode : e.keyCode; let re = /\d/; if ( !re.test(String.fromCharCode(charcode)) && charcode > 9 && !e.ctrlKey ) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } }); }, },
使用
?<input type="text" v-numInput ?/>
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
如何在vue-cli中使用css-loader實現(xiàn)css module
這篇文章主要介紹了如何在vue-cli中使用css-loader實現(xiàn)css module,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下2021-01-01