Search code examples
vue.jsdynamicv-model

Dynamicly bind v-model without extra array


I'm trying to create multiple vuetify-textfields with v-for and a template, so I can easily add and edit textfields while keeping my code clean.

Template Tag:

<template v-for="obj in textFieldProps">
  <v-text-field
    :ref="obj.ref"
    v-model="obj.model"
    :label="obj.lbl"
  ></v-text-field>
</template>

My current data looks like this:

export default {
  data: () => ({
    name: '',
    lastname: '',
    textFieldProps: [
      { ref: 'name', model: 'name', lbl: 'Name' },
      { ref: 'lastname', model: 'lastname', lbl: 'Lastname' }
    ]
  })
}

I know this question got asked multiple times, but every answer was: Dynamicly binding v-model works by creating an additional array, where in you safe your data (in my example name and lastname).

But this feels like a clunky workaround. So is there any way to directly bind v-model to this.name/this.lastname?


Solution

  • You can only bind v-model to one form input. To bind each input to a v-model, you must create an additional array when adding a new input field

    https://v2.vuejs.org/v2/guide/forms.html