0

I am using vue-bootstrap to make some input fields using a v-for directive. What I am trying to do is basically the same example provided in this link but I can't figure out how to get the data that I collect into a v-model directive (I mean, get the data from the inputs).

I could do it manually and assign every field and map it into a v-model for my object, but if there is a better way to solve this problem It would be very helpful.

This is the code (vue-js) copied almost exactly from the examples page but with my failed modifications (with comments):

<template>
  <b-container fluid>
    <code>{{result}}</code>
    <b-row class="my-1" v-for="type in types" :key="type">
      <b-col sm="3">
        <label :for="`type-${type}`">Type {{ type }}:</label>
      </b-col>
      <b-col sm="9">
        <!-- here I modified the v-model part -->
        <b-form-input :id="`type-${type}`" :type="type" :v-model="`result.${type}`"></b-form-input>
      </b-col>
      <!-- here I added the same "v-model" that I placed into the previous line -->
      <p>{{`result.${type}`}}</p>
    </b-row>
  </b-container>
</template>

<script>
  export default {
    data() {
      return {
        // here I placed the result object and I expected to obtain something like this:
        /*
result: {
text: "the text",
password: "the password" 
...
...
}
        */
        result: {},
        types: [
          'text',
          'password',
          'email',
          'number',
          'url',
          'tel',
          'date',
          `time`,
          'range',
          'color'
        ]
      }
    }
  }
</script>

Could anyone please explain what am I doing wrong? I've tried to find the documentation of the "`type-${type}`" in the v-for statement, but I couldn't find that.

mgXD-2
  • 102
  • 7

1 Answers1

1

Initialize result as:

result: {
  text: '',
  password:, '',
  email: '',
  number: '',
  url: '',
  tel: '',
  date: '',
  time: '',
  range: '',
  color: ''
}

And in your template and v-model, use [] instead of . for key accessing, i.e. result.${type} => result[type].

Also note v-model by itself is a directive, so you don't need to use v-bind(:) here:

<b-form-input :id="`type-${type}`" :type="type" v-model="result[type]">
</b-form-input>
Psidom
  • 209,562
  • 33
  • 339
  • 356
  • It doesn't work. What I've done is that I initialized result as suggested and then changed the original line to this : `` but the result object is not updated on any input – mgXD-2 Oct 29 '19 at 22:49
  • Did you change this line `

    {{ result.${type} }}

    `?
    – Psidom Oct 29 '19 at 22:51
  • This is what i placed instead of that line `

    {{result[type]}}

    ` but it doesnt show anything now
    – mgXD-2 Oct 29 '19 at 22:54
  • 1
    for `v-model`, you don't need the colon in front. It's a directive by itself. just do `v-model="result[type]"`. – Psidom Oct 29 '19 at 22:56