Samantha
Samantha

Reputation: 139

How to access multiple variables in Vue v-for?

How to change the label in bootstrap-vue in an input group? I am ok with the input field, the issue I have is trying to change the label to different labels?

<template>
  <b-modal id="Transfer" centered title="Transfer">
    <b-container fluid>
      <b-row class="my-1" v-for="type in types" :key="type">
        <b-col sm="3">
          <label :for="`type-${type}`">Type <code>{{ type }}</code>:</label>
        </b-col>
        <b-col sm="9">
          <b-form-input :id="`type-${type}`" :type="type"></b-form-input>
        </b-col>
      </b-row>
    </b-container>
  </b-modal>
</template>
data: () => ({
  labels: [].concat('test', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7', 'test8', 'time', 'range', 'color'),
  types: [].concat('text', 'number', 'email', 'password', 'search', 'url', 'tel', 'date', 'time', 'range', 'color')
})

Upvotes: 1

Views: 665

Answers (1)

Dan
Dan

Reputation: 63129

Define your field data in one object (or array), then you can easily access all the data in the v-for. This way allows you to also store the models for the data itself which would have to be a 3rd array otherwise:

new Vue({
  el: "#app",
  data: () => ({
    fields: {
      test: { type: 'text', model: '' },
      test2: { type: 'number', model: '' },
      test3: { type: 'email', model: '' },
      test4: { type: 'password', model: '' },
      test5: { type: 'search', model: '' },
      test6: { type: 'url', model: '' },
      test7: { type: 'tel', model: '' },
      test8: { type: 'date', model: '' },
      test9: { type: 'time', model: '' },
      test10: { type: 'range', model: '' },
      test11: { type: 'color', model: '' }
    }
  }) 
});

An object is slightly easier to look up a field by name later, for example, when doing validation.

Then in your v-for you can access the type on field.type and the label as the loop index. And give each input a v-model="field.model":

<b-modal id="Transfer" centered title="Transfer">
  <b-container fluid>
    <b-row class="my-1" v-for="(field, label) in fields" :key="label">
      <b-col sm="3">
        <label :for="`type-${field.type}`">Type <code>{{ field.type }}</code> {{ label }}:</label>
      </b-col>
      <b-col sm="9">
        <b-form-input :id="`type-${field.type}`" v-model="field.model" :type="field.type"></b-form-input>
      </b-col>
    </b-row>
  </b-container>
</b-modal>

Upvotes: 2

Related Questions