[Vuejs]-Price input formatter

0👍

You can watch the price value for changes instead.

const
  parseValue  = (v) => parseInt(v.trim().replace(/\./g, ''), 10),
  formatValue = (v) => (v / 100).toFixed(2).replace(/^(\d)(?=\.)/, '0$1');

new Vue({
  el: '#app',
  data: {
    price: '00.00'
  },
  watch: {
    price(newValue, oldValue) {
      const parsed = parseValue(newValue);
      this.price = !isNaN(parsed) ? formatValue(parsed) : oldValue;
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>

<div id="app">
  <input type="number" v-model="price" step="0.01">
</div>

0👍

Don’t reinvent the wheel.

MDN: <input type="number">

new Vue({
  el: '#app',
  data: {
    price: 0
  },
  watch: {
    price(val) {
      this.price = Math.round(val * 100) / 100;
    }    
  },
  computed: {
    priceFormated() {
      return this.price.toLocaleString('en-US',
      {
          style:"currency", 
          currency:"USD",
          minimumIntegerDigits: 2,
          useGrouping: false
      });
    }
  }
});
#app { line-height: 2; }
[v-cloak] { display: none; }
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>

<div id="app">
  <input v-model="price" type="number" placeholder="1.0" step="0.01" min="0" max="10" /><br/>
  <button @click="price -= 1">-1</button>
  Price: {{priceFormated}}
  <button @click="price += 1">+1</button>
</div>

Leave a comment