How to update value from v-for="(value,key) in obj" in vue-js

Viewed 1294

i have object with key value pair and I am using for loop on it.

     <CCol
            sm="6"
            v-for="(
              my_value, my_key
            ) in my_obj"
            :key="my_key"
          >
            <CInput
              :label="my_key"
              type="text"
              :placeholder="my_value" // I can use my_value as the placeholder
              :v-model="my_value" // but if I use my_value in v-model it gives an error
            />
          </CCol>

I am trying to display key as a label and value as the value of textbox and user can be able to update the value.

when I use value in v-model it gives an error "v-model' directives cannot update the iteration variable 'my_value' itself." but I can use it for the display purpose only like placeholder.

I need the value updatable.

Any suggestions are welcome. Thanks in advance.

1 Answers

Try to add the index then you could use the key to refer to the respective value :

  <CCol
            sm="6"
            v-for="(
              my_value, my_key,index
            ) in my_obj"
            :key="my_key"
          >
            <CInput
              :label="my_key"
              type="text"
              :placeholder="my_value" 
              v-model="my_obj[my_key]" 
            />
          </CCol>

when you iterate over an object like :

user:{
  first_name:'John',
  last_name:'Doe'
  age:25
}

the syntax v-for="(val,index) in user" will give you the each value and its index, but when you do v-for="(val,key,index) in user" this will give you the value, its key and index.

the right binding is v-model="object[key]" which could represent user.age, the wrong binding is to use v-model="val" and val in this case is available only in template like 25 or Doe which doesn't exist in script as property

Related