Rai
Rai

Reputation: 193

VueJS multiple selection

I tried to multiple select with select2 i used laravel and my data on userRoles is returned data on User model with relation roles, and allRoles is just all in Role model code on view

<select class="form-control" name="roles[]" id="roles"  multiple>
            <option v-for="role in allRoles"
                    :value="role.id"
                    >
                @{{ role.name }}
            </option>
 </select>

how to set selected options using userRoles array?

Upvotes: 1

Views: 1186

Answers (1)

JJPandari
JJPandari

Reputation: 3522

Add a computed hashMap (object) to search for selected roles:

computed: {
    selectedRoleMap() {
        var map = {};
        this.userRoles.forEach(role => {
            map[role] = 1;
        });
        return map;
    }
}

Then add :selected="selectedRoleMap.hasOwnProperty(role.id)" to options.

Working fiddle here: https://jsfiddle.net/df7j8xhz/

Alternatively, you can add a hasRole method to loop through userRoles to see if an id is in userRoles, but build a hashMap and search in it has a better performance than looping the array allRoles.length times.

Upvotes: 1

Related Questions