我的输入很简单,只需要整数,但是如果我使用e.preventDefault()
并返回到stop输入事件,则输入事件仍然有效。
input
v-on:input="changeFraction"
name="denominator"
type="text"
v-bind:value="fraction.denominator"
data() {
return {
fraction: {
numerator: '',
denominator: '',
},
};
},
methods: {
changeFraction(e) {
const el = e.target;
if (!/[0-9]/g.test(el.value)) {
e.preventDefault();
return null;
}
this.fraction[el.name] = el.value;
},
},
答案 0 :(得分:1)
当输入无效时,只需使用computed
进行验证,null
进行@input
事件。
例如:
<input type="text" v-model="fraction.numerator" @input="numeratorValid ? changeFraction : null"/>
computed: {
numeratorValid () {
return Number.isInteger(this.fraction.numerator)
}
}
答案 1 :(得分:0)
<template>
<div class = "fraction">
<input
@change = "changeFraction"
name = "numerator"
type = "number"
v-model.number = "fraction.numerator"
/>
<input
@change = "changeFraction"
name = "denominator"
type = "number"
v-model.number = "fraction.denominator"
/>
</div>
</template>
<script>
export default {
name: 'FractionItem',
data() {
return {
fraction: {
numerator: '',
denominator: '',
},
};
},
methods: {
changeFraction(e) {
const el = e.target;
//need add plus before value, because writting letter in input change data value to string type
if (!/[0-9]/g.test(+this.fraction[el.name])) {
e.preventDefault();
}
this.$parent.changeFractionInput({
id: this.id,
[el.name]: +this.fraction[el.name],
key: el.name,
});
},
},
};
</script>
<style lang = "scss" scoped></style>