Search code examples
javascriptvue.jsvuejs3vue-composition-api

format numbers from an array into an input


I have two inputs and an array with two positions in which both are numbers, in each input its v-model will make a value of the array in each position, writing in each input changes the heat in the array and this is fine.

I am trying to write in each input to format it and add commas of thousands and millions but keeping the value in the array without format and of type number, I have a function that formats it well in the console, but I cannot show it in the input, how can I achieve this?

<template>
  <input 
    type="text" 
    class="text-center" 
    v-model="rangePrice[0]"
  /> 
  <input 
    type="text" 
    class="text-center" 
    v-model="rangePrice[1]"
  />
</template>

<script setup>
const rangePrice = ref([0, 100000000])

// this function displays the formatted value to the console
const format = (e) => {
  console.log(rangePrice.value[0].toString().replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","))
}
</script>

I am using vue form slider where I have two scroll points and these two minimum and maximum values are the values of the array, which when moving the bar converts the values to a number:

<Slider
 class="slider"
 v-model="rangePrice"
 :lazy="false"
 :min="0"
 :max="100000000"
 :tooltips="false"
/>

Solution

  • Try with @input and :value instead v-model:

    const { ref } = Vue
    const app = Vue.createApp({
      setup() {
        const rangePrice = ref([0, 100000000])
        const format = (e) => {
          return e.toString().replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
        }
        const saveInput = (e, i) => {
          rangePrice.value[i] = parseInt(e.target.value.replaceAll(',', ''))
        }
        return {
          rangePrice, format, saveInput
        };
      },
    })
    app.mount('#demo')
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
    <div id="demo">
      <input 
        type="text" 
        class="text-center" 
        :value="format(rangePrice[0])"
        @input="saveInput($event, 0)"
      > 
      <input 
        type="text" 
        class="text-center" 
        :value="format(rangePrice[1])"
        @input="saveInput($event, 1)"
      > 
      {{rangePrice}}
    </div>