1

I have a select element within a vue component that looks like this:

<template>
    <select v-model="item.value" >
        <option value="1">A</option>
        <option value="2">B</option>
    </select>
    <div>
        You selected {{item.text}} with a value of {{item.value}}
    <div>
</template>
<script>
    export default {
        data() {
            return {
                item: {
                    text: '',
                    value: 0
                }
            }
        }
    }
</script>

If I make a selection, on A, I get a value of 1, if I make a selection on B. I get a value of 2. So item.value will be populated. How do I fill up item.text?

If I remove the value attribute from the options, I get the answer, but now my value wouldn't be populated.

1 Answer 1

2

I'd recommend using an array of objects that hold both the value and text for each <option>. For example

data() {
  return {
    // ...
    options: [
      { value: 1, text: 'A' },
      { value: 2, text: 'B' }
    ]
  }
}

Then you can use a v-for to iterate this list and simply bind the selected item with v-model

<select v-model="item">
  <option v-for="opt in options" :key="opt.value" :value="opt">
    {{opt.text}}
  </option>
</select>

See https://v2.vuejs.org/v2/guide/forms.html#Select-Options

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

1 Comment

That's such a weird work around, I see why this works though, the value attribute on each option gets an object rather than the value, and when you select a model, it selects that object. I'm really not a fan of this, but at least it works. Thanks!

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.