我想為輸入事件制作一個通用處理程式,我需要以某種方式更改其中的 v-model 值。我試過這個:
function validateInput(event) {
let input = event.target.value;
input = parseInt(input);
if(isNaN(input)) {
event.target.value = '';
} else {
event.target.value = input;
}
}
<input @input="validateInput($event)"
v-model="inputRef">
但inputRef不會對event.target.value變化做出反應。
uj5u.com熱心網友回復:
正如 Boussadjar 提到的,修改event.target.value是沒有選擇的。
只需從事件處理程式回傳值:
function onlyNumbersFilter(event) {
let input = event.target.value;
input = parseInt(input);
return isNaN(input) ? '' : input;
}
并使用它:
<input @input="inputRef = onlyNumbersFilter($event)" :value="inputRef">
或者,如果您想堅持v-model:
// setup
import { computed, ref } from 'vue'
// val is not DOM Event but value itself unwrapped from $event.target.value
function onlyNumbersFilter(val) {
const n = parseInt(val);
return isNaN(n) ? '' : val;
}
const filteredModel = function(valueRef, filterFn) {
return computed({
get() { return valueRef.value }
set(newVal) { valueRef.value = filterFn(newVal)) }
})
}
const input1Value = ref('')
const input1Model = filteredModel(input1Value, onlyNumbersFilter)
return {
input1Model
}
和用法:
<input v-model="input1Model">
uj5u.com熱心網友回復:
在這種情況下,您應該使用value而不是v-model因為v-model等效于@inputant value:
function validateInput(event) {
let input = event.target.value;
input = parseInt(input);
if(isNaN(input)) {
inputRef.value = '';
} else {
inputRef.value = input;
}
}
<input @input="validateInput($event)"
:value="inputRef">
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/448430.html
標籤:Vue.js
上一篇:具有引數值的重復鍵
下一篇:圖片在上傳時不斷更改檔案型別
