Search code examples
vue.jsdayjs

Dayjs is not updating in vue v-for


In a component template I have the following code:

<v-col cols="6" v-for="(value, idx) in data[workingYear].monthValues" :key="idx">
  {{ idx }}
  <v-row class="ai-center">
    <!-- Month -->
    <v-col cols="2">{{
      dayjs(idx + 1, "M").format("MMM").ucfirst()
    }}</v-col>
    <!-- Value -->
    <v-col cols="10">
      <v-text-field
        class="mt-0 pt-0"
        hide-details="auto"
        min="0"
        suffix=",00"
        type="number"
        v-model="data[workingYear].monthValues[idx]"
        :label="$t('set')"
        :prefix="getCurrency(true)"
        :ref="'monthValue' + idx"
        :rules="[rules.required, rules.invalid]"
      />
    </v-col>
  </v-row>
</v-col>

data[workingYear].monthValues is initialized as new Array(12).fill("") so it is an array of 12 empty string elements; ucfirst() is a custom extension to String.prototype that capitalize the first char of a string.

I'm aspecting to find in the first v-col block an incremented month, but the result is the following: Wrong months

So, why {{ idx }} is incremented for every cycle as aspected but the month is always January? How can I fix this?


Solution

  • It seems that dayjs wants only strings as input date so write this is the solution: dayjs("" + (idx + 1), "M").format("MMM").ucfirst()

    By the way, at this point, the solution posted by Boussadjra Brahim is more elegant and readable, so +1 for the function.

    Thanks