What's the proper way to implement formatting on v-model in Vue.js 2.0

Please check this working jsFiddle example: https://jsfiddle.net/mani04/bgzhw68m/

In this example, the formatted currency input is a component in itself, that uses v-model just like any other form element in Vue.js. You can initialize this component as follows:

<my-currency-input v-model="price"></my-currency-input>

my-currency-input is a self-contained component that formats the currency value when the input box is inactive. When user puts cursor inside, the formatting is removed so that user can modify the value comfortably.

Here is how it works:

The my-currency-input component has a computed value - displayValue, which has get and set methods defined. In the get method, if input box is not active, it returns formatted currency value.

When user types into the input box, the set method of displayValue computed property emits the value using $emit, thus notifying parent component about this change.

Reference for using v-model on custom components: https://vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events


Here is a working example: https://jsfiddle.net/mani04/w6oo9b6j/

It works by modifying the input string (your currency value) during the focus-out and focus-in events, as follows:

<input type="text" v-model="formattedCurrencyValue" @blur="focusOut" @focus="focusIn"/>
  1. When you put the cursor inside the input box, it takes this.currencyValue and converts it to plain format, so that user can modify it.

  2. After the user types the value and clicks elsewhere (focus out), this.currencyValue is recalculated after ignoring non-numeric characters, and the display text is formatted as required.

The currency formatter (reg exp) is a copy-paste from here: How can I format numbers as money in JavaScript?

If you do not want the decimal point as you mentioned in question, you can do this.currencyValue.toFixed(0) in the focusOut method.

Tags:

Vue.Js