【问题标题】:VueJs Custom currency maskVueJs 自定义货币掩码
【发布时间】:2018-05-16 14:37:33
【问题描述】:

我的货币掩码出现了一些问题。

当我在字段中输入 10000 时,它会按预期格式化 10,000 但当我将焦点转移到另一个字段或按 Tab 时。掩码将逗号位置向左移动 1。即 10,000 变为 1,0000

您可以检查 codepan 的问题,有人可以帮我解决这个问题吗?

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

模板:

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

方法:

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);
},

【问题讨论】:

    标签: javascript vuejs2 vuetify.js


    【解决方案1】:

    您不需要keyupv-model,它们最终可能会造成冲突。我发现使用计算值(或带有格式化版本的手表)更容易。

    模板:

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

    脚本:

    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, ''));
          }
        }
      }
    })
    

    如果您有不止一个或两个,将这些输入转换为单独的(可重用)组件会有所帮助。

    这是我不久前制作的一个示例,它使用可以处理其他类型(如百分比)的组件,仅在模糊后进行格式化(因此您的逗号不会跳跃)并允许使用向上和向下键进行递增/递减

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

    【讨论】:

    • 这就是代码的作用,最后的链接作为示例将其放入可重用组件中
    • codepen 现在在更新任何格式化值时会发出警告:避免直接改变 prop,因为每当父组件重新渲染时,该值都会被覆盖。
    • 是的,它发出警告的原因是改变道具不是一个好习惯。如果您只想让警告消失,您可以使用vue.min.js 而不是vue.js。但更好的做法是创建一个内部数据变量来跟踪内部值的变化。在这种情况下,这不太可能导致问题,但最好遵守此类 vue 指导方针。
    • 我已更新该示例以使用内部值 (_value)
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    相关资源
    最近更新 更多