Show formatted value of v-model on input field

212 views Asked by At

I have a number input with a v-model binding. The v-model is a number in minutes. If minutes > 60, I want to show hours and minutes instead of only minutes and show inside the input. Besides my input, I have 2 buttons. One is to add 15 minutes, one is to subtract 15 minutes.

For example: When minutes === 59, it should show: 59m. When minutes === 61, it should show: 1h 1m.

Right now it shows 59 and 61. How can I do this (with/without) a v-model binding? I would like it to be an input so users can enter numbers by typing it in.

My code:

           <span class="input-wrapper">
            <button
              id="decrement"
              @click.prevent="clickDecrement(reden)"
            >
              <img
                alt=""
                class="min-icon"
                :src="minIcon"
              />
            </button>
            <span class="flex white-bg">
              <input
                id="quantity"
                v-model="minutes"
                type="number"
                min="1"
              />
              min</span
            >
            <button
              id="increment"
              @click.prevent="clickIncrement(reden)"
            >
              <img
                alt=""
                class="min-icon"
                :src="plusIcon"
              />
            </button>
          </span>
const clickDecrement = (minutes: number) => {
  minutes = minutes - 15;
};

const clickIncrement = (minutes: number) => {
  minutes = minutes + 15;
};
1

There are 1 answers

2
Ajay Raja On

Here the working code. I implemented using computed.

<script setup>
import { ref, computed } from 'vue';

const minutes = ref(0);

const displayTime = computed(() => {
  if (minutes.value < 60) {
    return `${minutes.value}m`
  } else {
    return `${Math.floor(minutes.value / 60)}h ${minutes.value % 60}m`
  }
})

const clickIncrement = () => {
  minutes.value += 15;
};
const clickDecrement = () => {
  minutes.value -= 15;
};

</script>

<template>
  {{ displayTime }}
  <span class="input-wrapper">
    <button :disabled="(minutes - 15) < 0" id="decrement" @click.prevent="clickDecrement">
      <img alt="" class="min-icon" :src="minIcon" /> </button>
    <span class="flex white-bg">
      <input id="quantity" v-model="minutes" type="number" min="1" />
      min</span>
    <button id="increment" @click.prevent="clickIncrement">
      <img alt="" class="min-icon" :src="plusIcon" />
    </button>
  </span>
</template>