简体   繁体   English

Vue.js 可以在用户输入数字时添加逗号吗?

[英]Can Vue.js add commas while user typing numbers?

I see this topic , But this is Jquery, how can I change it to Vue.js ?我看到了这个话题,但这是 Jquery,我如何将其更改为 Vue.js? Is v-on supported in Vue.js? Vue.js 支持 v-on 吗? Where is my mistake?我的错误在哪里?

<div id="vue">
    <input v-model="amountModel" v-on:keyup="AddCammas()" value="{{price}}">
</div>

<script>
   el: #vue,
   methods:{
      AddCammas : funtion(){
          if(event.which >= 37 && event.which <= 40) return;

          $(this).val(function(index, value) {
             this.message = this.amountModel
                .replace(/\D/g, "")
                .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
           });
      } 
   }   
</script>

You don't need jQuery at all for this.为此,您根本不需要 jQuery。 You watch your variable, and in the watch function, compute the reformatted version, then set it back to your variable using nextTick (so it's not mutating before the watch is complete).watch你的变量,在 watch 函数中,计算重新格式化的版本,然后使用nextTick将它设置回你的变量(所以它在 watch 完成之前不会发生变异)。

 new Vue({ el: '#vue', data: { price: 0 }, watch: { price: function(newValue) { const result = newValue.replace(/\\D/g, "") .replace(/\\B(?=(\\d{3})+(?!\\d))/g, ","); Vue.nextTick(() => this.price = result); } } });
 <script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.min.js"></script> <div id="vue"> <input type="text" v-model="price" />{{price}} </div>

To people who are looking for doing mask for multiple fields then it's kinda pain to use watch , so may be we can use v-money (docs included).对于正在寻找为多个领域做掩码的人来说,使用watch有点痛苦,所以也许我们可以使用v-money (包括文档)。 And check the demo here .并在此处查看演示。

If you are using Vuetify, a new light-weight library called ' vuetify-money ' has been published.如果你使用 Vuetify,一个名为“ vuetify-money ”的新轻量级库已经发布。 Super easy to use for money value inputs, it is a text field that will add commas as you type.超级容易用于货币价值输入,它是一个文本字段,会在您输入时添加逗号。 Here's a demo.这是一个演示。

All properties you use on a v-text-field can also be used, so it is easily customizable.您在 v-text-field 上使用的所有属性也可以使用,因此可以轻松自定义。

Step 1第 1 步

npm install vuetify-money --save

Step 2第 2 步

Create a src/plugins/vuetify-money.js file with the following content:使用以下内容创建一个 src/plugins/vuetify-money.js 文件:

import Vue from "vue";
import VuetifyMoney from "vuetify-money";
Vue.use(VuetifyMoney);
export default VuetifyMoney;

Step 3第 3 步

Add file to src/main.js :将文件添加到 src/main.js :

import "./plugins/vuetify-money.js";

(main.js is the file where you usually put this) (main.js 是你通常放这个的文件)

new Vue({render: h => h(App)
}).$mount('#app');

Step 4 Use it in your code !第 4 步在您的代码中使用它!

<template>
  <div>
    <vuetify-money
      v-model="value"
      v-bind:options="options"
    />
    Parent v-model: {{ value }}
  </div>
</template>
<script>
export default {
  data: () => ({
    value: "1234567.89",
    options: {
      locale: "ja-JP",
      prefix: "$",
      suffix: "",
      length: 10,
      precision: 2
    }
  })
};
</script>

You now have a text field that will add commas as you type while keeping the v-model values perfectly fine.您现在有一个文本字段,它将在您键入时添加逗号,同时保持 v-model 值完美无缺。 It also prevents any non-number inputs so you hardly need front-end validation checks excluding customized cases.它还可以防止任何非数字输入,因此除了自定义案例之外,您几乎不需要前端验证检查。

If you want to use your method, you can make your AddCammas method like this :如果你想使用你的方法,你可以像这样制作你的 AddCammas 方法:

AddCammas: function(event) {
  event.target.value = event.target.value.replace(",", ".");
}

There is a little thing to know about event listener in VueJS.关于 VueJS 中的事件侦听器,有一点需要了解。 You can access the event object in the handler, but for this, you need either to use this syntax v-on:keyup="AddCammas" (no parentheses), or this syntax v-on:keyup="AddCammas($event)" (useful when you have multiple parameters)您可以在处理程序中访问事件对象,但为此,您需要使用此语法v-on:keyup="AddCammas" (无括号),或使用此语法v-on:keyup="AddCammas($event)" (当你有多个参数时很有用)

I used Inputmask with vanilla, for vue 2, and it works perfectly.我在 vue 2 中使用了 Inputmask 和 vanilla,它工作得很好。 Inputmask输入掩码

    <script src="../src/assets/js/libs/jquery-inputmask/inputmask.min.js"></script>
  <script src="../src/assets/js/libs/jquery-nputmask/bindings/inputmask.binding.js">

<script>
  $(document).ready(function () {
    var selector = document.getElementById("txtOrderQty");
    var im = new Inputmask({ alias: "currency", digits: 0, allowMinus: false }
    im.mask(selector);
</script>

 <template> <div class="form-group"> <label :class="{required:$attrs.required}">{{ label }}</label> <input v-model="model" class="form-control" :class="{invalid : error}" type="text" pattern="\\d+((\\.|,)\\d+)?" v-bind="$attrs"> <div v-if="error" class="invalid-tooltip">{{ error[0] }}</div> </div> </template> <script> export default { name: "InputNumber", emits: ['update:modelValue'], inheritAttrs: false, props: {modelValue: '', error: '', label: ''}, computed: { model: { get() { // return this.modelValue ? this.modelValue.toString().replace(/(\\d)(?=(\\d\\d\\d)+(?!\\d))/g, "$1,") : this.modelValue return this.modelValue ? this.modelValue.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ",") : this.modelValue }, set(value) { this.$emit('update:modelValue', Number(value.replaceAll(',',''))) } }, } } </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM