用户输入数字时,Vue.js可以添加逗号吗? [英] Can Vue.js add commas while user typing numbers?

查看:412
本文介绍了用户输入数字时,Vue.js可以添加逗号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到这个 主题 ,但这是Jquery,我如何将其更改为Vue.js?在Vue.js中是否支持v-on我的错误在哪里。对不起我糟糕的英语。

I see this topic, But this is Jquery, How can I change it to Vue.js ? Is v-on supported in Vue.js Where is my mistake. Sorry for my terrible English.

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


推荐答案

你根本不需要jQuery。您观察您的变量,并在watch函数中计算重新格式化的版本,然后使用 nextTick (所以在手表完成之前它没有变异)。

You don't need jQuery at all for this. 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).

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>

这篇关于用户输入数字时,Vue.js可以添加逗号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆