1

I have a dropdown that is populated with an array of objects.

<select v-model="selectedLeague" v-on:change="chooseLeague()">
    <option v-for="league in model.leagues" v-bind:value="league">
        {{  league.name }}
    </option>
</select>

At initialization, selectedLeague is {}

I want to add a default option that is selected when the object is empty. I tried adding

<option disabled v-bind:value=null>Choose League</option>

But that will not work because it is never null. What can I add to check if the object is empty using data binding? I am using version 2.4.4 btw

1 Answer 1

2

Since selectedLeague is initially {}, you can use:

<option disabled v-bind:value="{}">Choose League</option>

Demo:

new Vue({
  el: '#app',
  data: {
    selectedLeague: {},
    model: {
    	leagues: [{name: 'leagueOne'},{name: 'leagueTwo'}]
    }
  },
  methods: {
    chooseLeague() { console.log('chooseLeague()', this.selectedLeague); }
  }
})
<script src="https://unpkg.com/[email protected]"></script>

<div id="app">
  <select v-model="selectedLeague" v-on:change="chooseLeague()">
    <option disabled v-bind:value="{}">Choose League</option>
    <option v-for="league in model.leagues" v-bind:value="league">
      {{ league.name }}
    </option>
  </select>
</div>



Note: you can also add hidden if you want to hide that option from the dropdown:

<option disabled v-bind:value="{}" hidden>Choose League</option>
Sign up to request clarification or add additional context in comments.

1 Comment

Well TIL, that was easy!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.