1

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, i.e. '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?

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

Comments

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.