user2191247
user2191247

Reputation:

Vue.js, how to use v-model with an array of data?

Let's say I have an array of data:

this.data = [
    {
        id: 101,
        firstName: 'Alice',
        lastName: 'Smith',
        dob: '1995-12-10'
    },
    {
        id: 102,
        firstName: 'Reginald',
        lastName: 'Wernst',
        dob: '1979-10-03'
    },
    {
        id: 103,
        firstName: 'Jolanda',
        lastName: 'Finnbogadóttir',
        dob: ''
    }
]

I can put the data into cards, no problem. And I can recognize the card clicked, retrieve the id, and trace it back to the data, let's say index == 1, so the data I want is data[index] or { id: 102, firstName: 'Reginald', lastName: 'Wernst', dob: '1979-10-03' }.

But then I want to be able to populate a form with the data to update it. What should v-model look like? I tried all kinds of combinations. Mostly, it tells me stuff like data, index or whatever is not defined, so how to get the data out and back in?

<v-dialog v-model="data[index]???" persistent>
    <v-text-field v-model="id???" readonly></v-text-field>
    <v-text-field label="First Name" v-model="firstName???"></v-text-field>
    <v-text-field label="Last Name" v-model="lastName???"></v-text-field>
    <v-text-field label="Date of Birth" v-model="dob???"></v-text-field>
    <v-btn>Close</v-btn>
</v-dialog>

Upvotes: 0

Views: 728

Answers (1)

akuiper
akuiper

Reputation: 215117

The value or v-model on v-dialog controls the visibility, not specific data it's binding to; So you need to pass a property whose value you flips while clicking your cards:

Essentially:

<script>
export default {
  data () {
    return {
      arrData: [
        {
          id: 101,
          firstName: 'Alice',
          lastName: 'Smith',
          dob: '1995-12-10'
        },
        {
          id: 102,
          firstName: 'Reginald',
          lastName: 'Wernst',
          dob: '1979-10-03'
        },
        {
          id: 103,
          firstName: 'Jolanda',
          lastName: 'Finnbogadóttir',
          dob: ''
        }
      ],
      dialog: false,
      index: null
    }
  },
  methods: {
    clickCard (index) {
      this.index = index
      this.dialog = !this.dialog
    }
  }
}
</script>

And your template:

<template>
  <v-dialog v-model="dialog" persistent>
    <v-text-field v-model="arrData[index].id" readonly></v-text-field>
    <v-text-field label="First Name" v-model="arrData[index].firstName"></v-text-field>
    <v-text-field label="Last Name" v-model="arrData[index].lastName"></v-text-field>
    <v-text-field label="Date of Birth" v-model="arrData[index].dob"></v-text-field>
    <v-btn>Close</v-btn>
  </v-dialog>
</template>

Upvotes: 2

Related Questions