How to set the selected option in Vue.js 2?

Sometimes, we want to the set selected in Vue.js 2.

In this article, we’ll look at how to the set selected in Vue.js 2.

How to set the selected option in Vue.js 2?

To set selected option selected in Vue.js 2, we set the v-model variable to the selected option’s value attribute value.

For instance, we write

<template>
  <select v-model="selectedDay">
    <option v-for="day in days">{{ day }}</option>
  </select>
</template>

<script>
export default {
  data() {
    return {
      selectedDay: 1,
      days: Array.from({ length: 31 }, (v, i) => i).slice(1),
    };
  },
  mounted() {
    const selectedDay = new Date();
    this.selectedDay = selectedDay.getDate();
  },
};
</script>

to add the select drop down in the template.

We render the days values as options with v-for.

Then we define the days array in the data method.

Next, we set this.selectedDay to today’s date that we get from calling getDate on the current date which is selectedDay.

Conclusion

To set selected option selected in Vue.js 2, we set the v-model variable to the selected option’s value attribute value.