Travis Bear
Travis Bear

Reputation: 13859

How do you set a selected <option> based on runtime criteria

This code works great:

<select v-model="selected_service">
  <option>- select one -</option>
  <option v-for="service in services">{{ service }}</option>
</select>

But how do I make one of the <option> tags inside the v-for loop be selected, based on variables that are not known until runtime?

edit

The critera for selection is a field on the service object that may or may not be defined.

Upvotes: 1

Views: 81

Answers (1)

tony19
tony19

Reputation: 138226

As @Bert indicated, you can bind the value of your <option>s with v-bind:value="NEWVALUE" or the shorthand :value="NEWVALUE". In your case: <option :value="service">.

new Vue({
  el: '#app',
  data: {
    services: [
      'service 1',
      'service 2',
      'service 3'
    ],
    selected_service: 'service 2'
  }
})
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
  <select v-model="selected_service">
    <option>- select one -</option>
    <option v-for="service in services" :value="service">{{service}}</option>
  </select>
  <div>Selected service: {{selected_service}}</div>
</div>

Upvotes: 1

Related Questions