vue: `v-model.number` will set data to string when input[type="number"] value is empty
http://jsfiddle.net/SebastianBlade/krbjt745/
When input value is empty, num will turn to string type.
Is it a feature? I think number data should be 0 when input value is empty…
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Reactions: 3
- Comments: 21 (5 by maintainers)
Commits related to this issue
- Let empty number input work as expected. Please see: https://github.com/vuejs/vue/issues/4742 — committed to gansoi/gansoi by abrander 7 years ago
Yes a
[type="number"]which is emptied by a user should benullin my opinion. Setting it to empty string throws lots of type warnings if you have component props which expectNumberOr maybe there could be a
v-model.nullmodifier which could be used in various scenarios to set empty strings tonullif the user has emptied the input.I guess unexists value for the int typed property should be null instead of empty string.
I also agree that casting to null would make more sense… .number has a contract that you’ll get back a number…if it can’t be a number, it should be null…not an abrogation of the contract.
Please re-open this.
<input v-model.number="k" ...>should set k tonullif the input is updated and then cleared.nullis the idiomatic Javascript to indicate that no value is provided. Various JSON parsers acceptnullfor any field type, but not empty-string.Given
struct { int k; }this JSON does not decode:{"k":""}but this often does:{"k":null}@defcc @posva
@defcc @fergaldoyle any update on this?
@blade254353074 looks like its not just me that doesn’t agree that v-model.number should ever be returned as a string, i still hold strongly on thinking that the property should be removed from the object or turned null.
+1 for returning
nullwithv-model.number. As mentioned by @fergaldoyle, a.nullmodifier would be cool.@defcc any chance this could get re-opened?
@defcc I think this is still worth a conversation. I completely agree that casting to 0 seems incorrect, but what is the use case of this modifier? I think most people would use this thinking now I don’t need the extra step of casting the string to an integer because some child component expects and integer not a string. But currently it falls back to a string which means you still need that extra code to ignore it if the cast fails making it significantly less useful. Is there a reason its not cast to undefined or null?
It is an expected behavior. Vue will try to cast the string to number type, it will return the original string if it fails.
And it’s also reasonable, or you will always get 0 after you delete the input value. As for your case, it’s better to deal with it in the userland.