Search code examples
vue.jsvuetify.jsv-forv-select

Loop options values in v-select using v-for, is it doable?


I am new at VueJS and using vuetify to do a select dropdown. I am getting a variable from the DB and would like to generate the options using a v-for if possible. I was not able to make it work, so the solution I used is below, but I think it could be done in a more effective way.

<v-select 
   v-show="pgto.tipo === 'credito'"
   v-if="input.jornada.parcelas === 6"
   v-model="pgto.parcelas"
   :items="['1','2','3','4','5','6']"
   label="Parcelas"
   required
   />
<v-select
   v-show="pgto.tipo === 'credito'"
   v-if="input.jornada.parcelas === 5"
   v-model="pgto.parcelas"
   :items="['1', '2', '3', '4', '5']"
   label="Parcelas"
   required
   />
<v-select
   v-show="pgto.tipo === 'credito'"
   v-if="input.jornada.parcelas === 4"
   v-model="pgto.parcelas"
   :items="['1', '2', '3', '4']"
   label="Parcelas"
   required
   />
<v-select
   v-show="pgto.tipo === 'credito'"
   v-if="input.jornada.parcelas === 3"
   v-model="pgto.parcelas"
   :items="['1', '2', '3']"
   label="Parcelas"
   required
   />
<v-select
   v-show="pgto.tipo === 'credito'"
   v-if="input.jornada.parcelas === 2"
   v-model="pgto.parcelas"
   :items="['1', '2']"
   label="Parcelas"
   required
   />
<v-select
   v-show="pgto.tipo === 'credito'"
   v-if="input.jornada.parcelas === 1"
   v-model="pgto.parcelas"
   :items="['1']"
   label="Parcelas"
   required
   />

I am getting input.jornada.parcelas from the DB. My initial idea was to do something like this JS, but with v-select:

for(var i = 1; i <= input.jornada.parcelas; i++){
      "<option value='" + i + "'>" + i + "</option>";
    }

my try:

<v-select
    v-show="pgto.tipo === 'credito'"
    v-model="pgto.parcelas"
    :options v-for="n in input.jornada.parcelas" {{ n }}> 

As you can see I am not evolving well... Any suggestions, references or ideas?


Solution

  • What are you are trying to do is not how Vue works, thus it won't work.

    Instead of generating the option tags, you should be modifying your data and binding that to v-select.

    I would generate the list values either via a computed property or load the data, and keep it as a variable in data, if it is only used once.

    Assuming that the data is dynamic, and will change, you would use a computed property.

    computed:{
       options(){
          let opts = [];
          for(let i = 1; i <= input.jornada.parcelas; i++){
              opts.push({text:i, value:i});
          }
          return opts
       }
    }
    

    Then you would bind the computed value to items and vuetify will handle the rest.

    <v-select
        v-show="pgto.tipo === 'credito'"
        v-model="pgto.parcelas"
        :items="options"
    >