Vue.js v-for set Option Selected

I recently started working with Vue.js. I found it to be quite a well engineered product and a well designed framework. In the framework, one can use a v-for attribute within markup to to loop over data stored in their view model and with each iteration generate more markup. I was utilizing the v-for to loop over data to create <options> for a drop-down menu – a common usage – and I wanted to set a specific option to be selected.

Example

Let’s use the following example.

<select>
    <option v-for="item in items">
        {{item}}
    </option>
</select>

If our items contains item1, item2, item3; we will create the following drop-down.

Solution

If we wanted the second item (item 2) to be the default we’d do this.

<select>
    <option v-for="item in items" :selected="item === 'item 2'? true : false">
        {{item}}
    </option>
</select>

And now the default would be set to item 2.

Leave a Reply

Your email address will not be published. Required fields are marked *