Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vue.js

For a simple example: textbox to input currency data. The requirement is to display user input in "$1,234,567" format and remove decimal point.

I have tried vue directive. directive's update method is not called when UI is refreshed due to other controls. so value in textbox reverts to the one without any formatting.

I also tried v-on:change event handler. But I don't know how to call a global function in event handler. It is not a good practice to create a currency convert method in every Vue object.

So what is the standard way of formatting in Vue 2.0 now?

Regards

like image 777
flyfrog Avatar asked Dec 13 '16 02:12

flyfrog


People also ask

How does V-model work in Vue?

Vue v-model is a directive that creates a two-way data binding between a value in our template and a value in our data properties. A common use case for using v-model is when designing forms and inputs. We can use it to have our DOM input elements be able to modify the data in our Vue instance.

What is Vue format?

A VUE (. vue) file is an editable ASCII file. You create a VUE file using the VUE file renderer. A VUE file contains a sequence of frames to render.

What is V-model lazy in Vue?

.lazy. By default, v-model syncs the input with the data after each input event (with the exception of IME composition as stated above). You can add the lazy modifier to instead sync after change events: template <!--


1 Answers

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

like image 117
Mani Avatar answered Sep 26 '22 03:09

Mani