Bill Muxworthy
Bill Muxworthy

Reputation: 133

Vue 3 Select-Option, make first option the default

I'm trying to make the first select option default, therefore showing right away when the page loads. I thought since v-bind:selected is a booleanish attribute I could just use something simple like index === 0 to select the first by default but this doesn't seem to be working, and there is no option selected on page load. I've debugged and the indexes are incrementing normally, there's nothing weird going on there. Is there just something silly I'm missing maybe? selectedThingId is a ref with a default value of zero. I've also looked in the html changing this number and nothing is ever selected!

Here's the template code:

<select name="select" id="select" v-model="selectedThingId" @change="onChangeFunction">
    <option v-for="(thing, index) in things"
        :value="thing.id"
        :key="thing.id"
        :selected="index === 0"
    >
        {{ thing }}
    </option>
</select>

Upvotes: 3

Views: 1966

Answers (1)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23500

Try to set selectedThingId in onMounted hook :

const { ref, reactive, onMounted } = Vue
const app = Vue.createApp({
  setup() {
    const selectedThingId = ref(null)
    const things = reactive([{id: 3, name: 'aaa'}, {id: 5, name: 'bbb'}, {id: 9, name: 'ccc'}])
    
    onMounted(() => selectedThingId.value = things[0].id)
    
    const onChangeFunction =() => {}
    return { things, selectedThingId, onChangeFunction }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <select name="select" id="select" v-model="selectedThingId" @change="onChangeFunction">
    <option v-for="(thing, index) in things" :key="thing.id"
      :value="thing.id"
    >
      {{ thing.name }}
    </option>
  </select>
  {{ selectedThingId }}
</div>

Upvotes: 0

Related Questions