Home > Net >  Dayjs is not updating in vue v-for
Dayjs is not updating in vue v-for

Time:02-10

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 >
    <!-- Month -->
    <v-col cols="2">{{
      dayjs(idx   1, "M").format("MMM").ucfirst()
    }}</v-col>
    <!-- Value -->
    <v-col cols="10">
      <v-text-field
        
        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?

CodePudding user response:

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

CodePudding user response:

I suggest to use a computed property that returns a function which takes the index as parameter and return the month:

    <v-col cols="2">{{
      getMonth(idx)
    }}</v-col>

script:

computed:{
  getMonth(){
   return (idx)=>dayjs(`${idx   1}`, "M").format("MMM").ucfirst()
 }
}
  • Related