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

前端 未结 4 1377
耶瑟儿~
耶瑟儿~ 2021-02-05 02:45

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 direct

4条回答
  •  不知归路
    2021-02-05 03:25

    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 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

提交回复
热议问题