Vue.js,如何对数据数组使用v模型?

时间:2018-12-17 19:28:41

标签: vue.js persistence

假设我有一个数据数组:

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: ''
    }
]

我可以将数据放入卡中,没问题。而且我可以识别出单击的卡,检索id,然后将其追溯到数据,例如index == 1,所以我想要的数据是data[index]{ id: 102, firstName: 'Reginald', lastName: 'Wernst', dob: '1979-10-03' }

但是随后,我希望能够用数据填充表单以对其进行更新。 v-model应该是什么样?我尝试了各种组合。通常,它会告诉我诸如dataindex之类的东西或未定义的内容,那么如何获取和返回数据呢?

<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>

1 个答案:

答案 0 :(得分:3)

value上的v-modelv-dialog控制可见性,而不是其绑定的特定数据;因此,您需要传递一个属性,该属性在单击卡片时会翻转其值:

本质上:

<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>

以及您的模板:

<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>