isatrio
isatrio

Reputation: 15

How to show multi dimension array to one level select options using v-for in Vue JS

Let say I have an array structured below

[
    { 
        id: 0, 
        name: 'Global'
    },
    { 
        id: 1,
        name: 'Africa',
        sub_regions: [
            {
                id: 2,
                name: "East Africa",
                countries: [
                    {
                        id: 3,
                        name: "Burundi"
                    },
                    {
                        id: 4,
                        name: "Comoros"
                    }
                ]
            }
        ]
    },
    {
        id: 5,
        name: "Asia",
    }
]

What I want to do is like below

<select>
    <option>Global</option>
    <option>Africa</option>
    <option>Burundi</option>
    ..
</select>

I've tried using v-for like below

<select>
    <option value="region.id" v-for="region in regions">region.name</option>
</select>

Then confuse how to show the sub region. The important thing is user can select all region/sub region/country. Stuck in all day long. please someone maybe can help me.

Thanks in advance

Upvotes: 0

Views: 335

Answers (2)

isatrio
isatrio

Reputation: 15

Actually I'm just know how to do it, i'm exploring again on the internet and found the answer (finally). It use <template> tag like below

<select>
    <template v-for="region in regions">
        <option :value="region.id">{{ region.name }}</option>
        <template v-if="region.sub_regions" v-for="subregion in region.sub_regions">
            <option :value="subregion.id">{{ subregion.name }}</option>
            <template v-if="subregion.countries" v-for="country in subregion.countries">
                <option :value="country.id">{{ country.name }}</option>
            </template>
        </template>
    </template>
</select>

Upvotes: 0

puelo
puelo

Reputation: 5977

You can use a templates to iterate through each reagion and inside that template through each sub-region:

  <select>
    <template v-for="region in regions">
        <option :value="region.id">{{region.name}}</option>
        <template v-for="subregion in region.sub_regions">
          <option :value="subregion.id" v-for="subregion in region.sub_regions">{{subregion.name}}</option>
          <option :value="country.id" v-for="country in subregion.countries">{{country.name}}</option>
        </template>
    </template>
  </select>

https://jsfiddle.net/cckLd9te/2926/

Upvotes: 1

Related Questions