Home / VueJS

Vuejs V-model Automatically Converts Input Strings to Numbers

Posted on:2020-03-02 Views:8556 Words:110

JS type conversion bugs

Even if type = “number” is specified in the HTML input input input box, it often occurs that the value obtained by V-model is a string.

Thus, in the numerical calculation logic, add number to string will cause bug.

> 100 + "2.35"
"1002.35"

What we expect is:

> 100 + 2.35
102.35

In money related calculations, this is very dangerous.

Therefore, you have to use parsefloat() or number() to convert strings.

Vuejs automatic conversion

<input v-model.number="price" type="number">

This is much more convenient.

A similar feature is v-model.trim.

Reference for reference

https://vuejs.org/v2/guide/forms.html#number