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

前端 未结 4 1396
耶瑟儿~
耶瑟儿~ 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:47

    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:

    
    
    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.

提交回复
热议问题