简体   繁体   中英

Vuejs - Use key in object loop as option value

I have a colors object, that contains exactly what you think:

{
  "RD": "Red",
  "BL": "Blue",
  "GR": "Green",
  "YW": "Yellow"
}

I have a select dropdown that creates an <option> for each color in the colors object:

<select v-model="colors">
  <option selected>SELECT A COLOR</select> // default value
  <option v-for="(color, key) in colors">{{ color }}</option>
</select>

This displays great in the dropdown.

  • The {{ color }} expression shows the name, ie ' Blue '
  • If I were to instead use {{ key }} as the expression, it would read ' BR '

Challenge:

  • I am struggling to assign key to the option value attribute

For example:

<option v-for="(color, key) in colors" :key="key">{{ color }}</option>

In this case key is actually 'Blue' instead of 'BR', and switching it to color shows the same thing. What am I doing wrong?

Try the following with setting value property via :value :

<select v-model="colors">
  <option selected>SELECT A COLOR</select>
  <option v-for="(color, key) in colors" :value="key" :key="key">{{ color }}</option>
</select>

Here is a JSFiddle demonstrating the functionality.

Hopefully that helps!

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