1、使用v-model指令
<input type="number" v-model="value" min="0" @input="checkInput">
checkInput() {
this.value = Math.max(0, parseInt(this.value));
}
2、使用计算属性
<template>
<div>
<input type="number" v-model="value" @input="updateValue" />
</div>
</template>
<script>
export default {
data() {
return {
value: 0
};
},
computed: {
checkedValue: function() {
return Math.max(0, this.value);
}
},
methods: {
updateValue: function(event) {
this.value = parseInt(event.target.value);
}
}
};
</script>
3、使用自定义指令
<template>
<div>
<input v-negative-number v-model="value" />
</div>
</template>
<script>
export default {
data() {
return {
value: 0
};
},
directives: {
"negative-number": function(el, binding) {
el.addEventListener("input", function(event) {
var currentValue = parseInt(event.target.value);
if (currentValue < 0) {
event.target.value = 0;
return binding.value;
} else {
event.target.value = currentValue;
return currentValue;
}
});
}
}
};
</script>