Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ? Is v-on supported in Vue.js? 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>
like image 600
Morteza Negahi Avatar asked Nov 29 '22 00:11

Morteza Negahi


1 Answers

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>
like image 106
Roy J Avatar answered Dec 16 '22 07:12

Roy J