0

I have data like this - the keys for the phone object can be "mobile", "home"...

contacts[
  11:{
    name: "Mr Blobby"
    phone: {
      mobile: "07123 456789",
      home: "0201 2345 6789"
    }
    ...
  }
  ...{}

Displaying it (cRud) is easy:

<div v-for="contact in contacts" :key="contact.id" :contact="contact">
  <div v-for="(phone, type) in contact.phone" :key="type" :phone="phone">
    <b>{{ type }}</b>
    <h2>{{ phone }}</h2>
  </div>
</div>

But how do I bind specifically the key (mobile/home...) using a select and v-model (CrUd) ?

<div v-for="(phone, index) in contact.phone" :key="phone">
   <input type="tel" v-model.trim="contact.phone[index]" />
   <select v-model="???">
      <option value="mobile">Mobile</option>
      option value="home">Home</option>
   </select>
</div>

1 Answer 1

1

The code below should work if you want to iterate through the properties of the phone object. You can then bind the select value to a variable with v-model.

 <select v-model="selectedPhone">
  <option disabled value="">Select a phone</option>
  <option
   v-for="(value, name) in contact.phone"
   :key="value"
   :value="name"
  >
   {{ name }}
  </option>
 </select>

in v-for we provide the second argument 'name'(a.k.a. key) which will be 'mobile' or 'home' and then we set it as the options values. So we set the phone object keys as the options values which i think is what you're aiming for?


You should also declare the initial value of the v-model variable inside the data option of your component.

data () {
 return {
  selectedPhone: ''
 }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this - it does display the keys, which is what I was after.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.