简体   繁体   中英

how can I bind an object values to the dynamically added input field using vue Js

I have an object in an array which properties and values are dynamically added like this

  dataArray: [
    {
      first_name: "john",
      last_name: "doe",
      age: "45"
    }
  ]

I want to create input field corresponding to the object property so I do this

<input v-for="(item,index) in dataArray[0]" :key="index" v-model="item[index]"></input>

Input fields are created but how can I bind the value with the object property, i try to do with (v-model="item[index]") but its not working.

没有这样的数据item[index] ,请尝试:

v-model="dataArray[0][index]"

In your example, item is an object (dataArray[0]). Object properties don't have an index, so it's not possible to do what you're trying. item[index] is looking for a property key named "0", "1" and "2", which don't exist.

If all your objects in dataArray have different properties, you should create an array of the object keys using Object.keys() and use those to get all the property values. (see this question for examples).

No need for index in this case as the item already represents the value:

<input v-for="(item,index) in dataArray[0]" :key="index" v-model="item"></input>

However the issue with this approach is that your model won't be reactive. One way around it is to do it this way.

  1. Change your html to <input v-for="(item,index) in dataArray[0]" :key="index" @keyup="change(index, $event.target.value)"></input>

  2. Add change method to your Vue instance code: methods: { change(index, val) { this.dataArray[0][index] = val; console.log(index + ': ' + val); } } methods: { change(index, val) { this.dataArray[0][index] = val; console.log(index + ': ' + val); } }

I am actually would be curious to see what another solution for this might be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM