3

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

1
  • There's no choice but to get the id from the object you're trying to select. I would also recommend choosing a different key for you selected country, since now it overlaps with the key you've used inside the for loop. In the place where you're fetching the countries, you can also look up the id for the country you want to select (based on the ISO code) Commented Mar 7, 2021 at 10:34

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

this works like a charm, thanks for the code. That is what I had in my mind too. I have a mounted method indeed as you said. I just wanted to know if there is a vue.js way to alter selected option in v-for but probably that is the only workaround here.
You are welcome. I guess it is the only workaround. If you find something simpler share it. Good luck.

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.