Answer a question

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?

Answers

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

Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐