VueJs Custom currency mask

吃可爱长大的小学妹 提交于 2021-02-10 05:49:08

问题


My Currency mask has got some issues.

When I am typing say 10000 in the field, it formats it as expected 10,000 but the moment i shift focus to another field or press tab. The mask shifts the comma position to the left by 1. i.e. 10,000 becomes 1,0000

You can check codepan for the issue, can anyone help me with this?

https://codepen.io/veer3383/pen/BxqzLb?editors=1010#

The template:

<v-text-field @keyup="formatCurrency(initialBalance, $event)" :prefix="currency" v-model="initialBalance" label="Balance" :disabled="disabled"></v-text-field>

The method:

formatCurrency (num: any, e: any) {
    num = num + '';
    var number = num.replace(/[^\d.-]/g, '');
    var splitArray = number.split('.');
    var integer = splitArray[0];
    var mantissa = splitArray.length > 1 ? '.' + splitArray[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(integer)){
        integer = integer.replace(rgx, '$1' + ',' + '$2');
    }
    e.currentTarget.value = integer + mantissa.substring(0, 3);
},

回答1:


You don't need a keyup AND v-model, they may end up creating a conflict. I find it's easier to use a computed value (or a watch with a formatted version).

template:

<div id="app">
  <v-app id="inspire">
    <v-form ref="form" v-model="valid" lazy-validation>
    <v-flex lg3="">
      <v-text-field :prefix="currency" v-model="initialBalanceFormatted" label="Balance" :disabled="disabled"></v-text-field>
      </v-flex>
    </v-form>
  </v-app>
</div>

script:

function formatAsCurrency (value, dec) {
  dec = dec || 0
  if (value === null) {
    return 0
  }
  return '' + value.toFixed(dec).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
}

new Vue({
  el: '#app',
  data: () => ({
    valid: true,
    disabled: false,
    currency: "£",
    initialBalance: null,
  }),

  computed: {
    initialBalanceFormatted: {
      get: function() {
        return formatAsCurrency(this.initialBalance, 0)
      },
      set: function(newValue) {
        this.initialBalance =  Number(newValue.replace(/[^0-9\.]/g, ''));
      }
    }
  }
})

It helps to turn these inputs into separate (reusable) components if you have more than one or two.

Here's an example I made a while back that uses components that can handle other types like percentage, does formatting only after blured (so your comma is not jumping) and allows to use up and down key for increment/decrement

https://codepen.io/scorch/pen/oZLLbv?editors=1010



来源:https://stackoverflow.com/questions/50373777/vuejs-custom-currency-mask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!