Dennis Dasios
Dennis Dasios

Reputation: 33

Vue.js selected option not based on value

I have an json object returned from an API call like this:

"countries": [
{
  "id": 1,
  "iso": US,
  "name": "United States",
},
{
  "id": 2,
  "iso": FR,
  "name": "France",
},
{
  "id": 3,
  "iso": GB,
  "name": "United Kingdom",
},
]

In my vue component:

<select v-model="country">
    <option v-for="country in countries" :value="country.id">{{ country.name }}</option>
</select>

How can I have pre-selected the third json instance based on the iso code?

The following code inside v-for does not work

:selected="country.iso === 'GB'"

I could do of course

data: function () {
    country: 3
}

but I want to declare the default selected value based on iso code, not id.

I do not want to change iso as the model's value, as I am going to send it as post request to my API. If I did this, I could parse the whole json object to find the id from its iso code, but I am not sure this would be the cleanest solution.

Thanks

Upvotes: 3

Views: 104

Answers (1)

mare96
mare96

Reputation: 3869

You can do it after your API call, I guess you have it in mounted(), then just put value what do you need in country value.

Something like this:

mounted() {
    axios.get('your-api-call-for-countries').then(response => {
         // Assign data from ...
         this.countries = response
         // Find Object which you want to be pre selected...
         let selected = this.countries.find(i => i.iso === 'GB')
         // Use id for your v-model...
         this.country = selected.id

         // or simplier
         this.country = this.countries.find(i => i.iso === 'GB').id
    })
}

I think this is the only solution for doing that since you need id based on iso.

Upvotes: 1

Related Questions