Home > Net >  Vue - Dynamically add specific v-model name with v-for, not just an index
Vue - Dynamically add specific v-model name with v-for, not just an index

Time:02-18

I want to loop over the colorMenus array and bind my v-model to the already defined data elements headerColor and checkboxColor

I have this simplified code:

<v-card
  v-for="(colorMenu, index) in colorMenus"
  :key="index"
>
  <v-row>
    <v-col>
      <p >{{ colorMenu.title }}</p>
    </v-col>
    <v-col cols="8">
      <v-text-field 
        v-model="myModels.color[index]"
        v-mask="mask" 
        hide-details 
        
        solo
      ></text-field>
    </v-col>
  </v-row>
</v-card>

And my data looks like this:

export default {
  data() {
    return {
      headerColor: '#1976D2FF',
      checkboxColor: '#1976D2FF',
      myModels: {
        color: ['headerColor', 'checkboxColor']
      },
      colorMenus: [
        {
          title: 'HEADER:',
        },
        {
          title: 'CHECKBOX:',
        }
      ]
    }
  },

What's weird is I can get this, the model names, but they have # in front?

enter image description here

CodePudding user response:

I think that's because you've defined strings inside of that color array. You should refer to these items like this:

 myModels: {
     color: [this.headerColor, this.checkboxColor]
 },

CodePudding user response:

I hope this helps. in a v-for for some reason I cannot access the name from an array, but I can if I access the data by key from ANOTHER object. No idea why, but it worked! Here is the fixed code:

<v-card
  v-for="(colorMenu, index) in colorMenus"
  :key="index"
>
  <v-row>
    <v-col>
      <p >{{ colorMenu.title }}</p>
    </v-col>
    <v-col cols="8">
      <v-text-field 
        v-model="myModels[colorMenu.type]"
        v-mask="mask" 
        hide-details 
        
        solo
      ></text-field>
    </v-col>
  </v-row>
</v-card>

And then my data:

  export default {
    data() {
    return {
      headerColor: '#1976D2FF',
      checkboxColor: '#1976D2FF',
      myModels: {
        headerColor: '#1976D2FF',
        checkboxColor: '#1976D2FF',
      },
      colorMenus: [
        {
          title: 'HEADER:',
          type: 'headerColor'
        },
        {
          title: 'CHECKBOX:',
          type: 'checkboxColor'
        }
      ]
        }
    },
  • Related