Vue中輸入框僅支持數(shù)字輸入的四種方法
方法 1: 使用 @input 事件和正則表達式
通過監(jiān)聽 @input 事件并使用正則表達式來驗證輸入,只允許輸入數(shù)字。
<template>
<div>
<input type="text" v-model="inputValue" @input="validateInput" />
</div>
</template>
<script>
export default {
data() {
return {
inputValue: ''
};
},
methods: {
validateInput() {
// 只允許輸入數(shù)字
this.inputValue = this.inputValue.replace(/[^0-9]/g, '');
}
}
};
</script>
方法 2: 使用 @keypress 事件
通過監(jiān)聽 @keypress 事件來限制輸入,只允許輸入數(shù)字。
<template>
<div>
<input type="text" @keypress="allowOnlyNumbers" />
</div>
</template>
<script>
export default {
methods: {
allowOnlyNumbers(event) {
const char = String.fromCharCode(event.which);
// 允許輸入數(shù)字(0-9)
if (!/[0-9]/.test(char)) {
event.preventDefault(); // 阻止輸入
}
}
}
};
</script>
方法 3: 使用 @keydown 事件
使用 @keydown 事件來阻止輸入非數(shù)字字符。
<template>
<div>
<input type="text" @keydown="allowOnlyNumbers" />
</div>
</template>
<script>
export default {
methods: {
allowOnlyNumbers(event) {
// 允許的鍵碼:0-9
if (event.key < '0' || event.key > '9') {
event.preventDefault(); // 阻止輸入
}
}
}
};
</script>
方法 4: 使用 type=“number” 和 min 屬性
如果你使用 type=“number”,可以通過設(shè)置 min 屬性來禁止負數(shù)輸入,但這仍然允許用戶輸入小數(shù)。為了完全禁止小數(shù)和符號,結(jié)合 @input 事件進行驗證。
<template>
<div>
<input type="number" min="0" @input="validateInput" />
</div>
</template>
<script>
export default {
methods: {
validateInput(event) {
const value = event.target.value;
// 只允許輸入數(shù)字
if (!/^\d*$/.test(value)) {
event.target.value = value.replace(/[^0-9]/g, '');
}
}
}
};
</script>
以上方法可以有效地禁止用戶在 Vue 中的輸入框中輸入非數(shù)字字符。選擇適合你需求的方法來實現(xiàn)輸入限制。
總結(jié)
到此這篇關(guān)于Vue中輸入框僅支持數(shù)字輸入的文章就介紹到這了,更多相關(guān)Vue輸入框僅支持數(shù)字輸入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue登錄后添加動態(tài)路由并跳轉(zhuǎn)的實踐分享
這篇文章講給大家詳細介紹一下Vue如何實現(xiàn)登錄后添加動態(tài)路由并跳轉(zhuǎn),文章通過代碼示例介紹的非常詳細,對我們的學(xué)習(xí)或工作有一定的的幫助,需要的朋友可以參考下2023-07-07
詳解vue2.0監(jiān)聽屬性的使用心得及搭配計算屬性的使用
這篇文章主要介紹了vue2.0之監(jiān)聽屬性的使用心得及搭配計算屬性的使用,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-07-07
vue實現(xiàn)原理this.$message實例詳解
這篇文章主要介紹了vue實現(xiàn)原理this.$message實例詳解,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-03-03

