5

I'm trying to set default selected value for my dropdown list. My code looks like this:

        <select v-model="newSelectedUnit" @change="selectUnit(newSelectedUnit)" class="custom-select">
          <option v-for="unit in units" :key="unit.id" :value="unit.id" :selected="unit.id == Selectedunit.id">{{ unit.name }}</option>
        </select>

but there's no default selected value. I already tried to hardcoded Selectedunit.id to 32712 (which is one of the unit's IDs):

            <select v-model="newSelectedUnit" @change="selectUnit(newSelectedUnit)" class="custom-select">
              <option  v-for="unit in units" :key="unit.id" :value="unit.id" :selected="unit.id == 32712">{{ unit.name }}</option>
            </select>

In Chrome inspector there's an <option> tag with value of 32712:

<option value="32712">CYLINDER</option>

but it's not selected by default.

EDIT: I noticed that there's a problem with selected atribute. In above example, if i set another attribute: :selectedXXX="unit.id == 32712" i've got expected attribute in Chrome dev tools:

<option selectedXXX="true" value="32712">CYLINDER</option>

EDIT2: If I remove v-model="newSelectedUnit" I've got selected value set correctly! But why?

2 Answers 2

5

Use either "@change and :selected" or "v-model", but not both.

Now the v-model on <select> will try to select the unit based on the value in newSelectedUnit

If the initial value of your v-model expression does not match any of the options, the element will render in an “unselected” state.

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

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

1 Comment

Yup very clear - thank you! This is a tricky and very important concept to grasp when dealing with selects in Vue.
-1

If you are using materialize css template, it's with a

select { display:none }

add in your default app css

select: { display: block }

it'll appear again!

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.