Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue JS - Bind select option value to model inside v-for

Tags:

vuejs2

I have a table populated with an array of objects (mappedMenus).

MappedMenus is a class that has a propery named "menuTypeId".

The possible values for this property "menuTypeId" are set in an array of MenuTypes objects, that have an "id" and a "name" property.

With these MenuTypes objects, I populate the select for each row.

The problem I´m having, is that I don´t know how to bind the "menuTypeId" property of every MappedMenu object to its select selected option.

As you can see in my code, I do a v-for in the tr with my mappedMenus.

For every object, I have a row with a select with options. The options are populated using another array named menuTypes.

Then I tried to bind the select with the MappedMenu object in the loop (e.menuTypeId) and then bind the value in the option. I dont get any error with the following code, but I does not works either.

<table id="#divTable" class="uk-table">
    <thead>
        <tr>
            <th>Menu Type</th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="e in mappedMenus">
            <td>
                <select class="uk-select" v-model="e.menuTypeId">
                    <option v-for="m in menuTypes" v-bind:value="e.menuTypeId">{{m.name}}</option>
                </select>
            </td>
        </tr>
    </tbody>
</table>

<script>
var updateMenuVM = new Vue({
    el: '#divTable',
    data: {
        menuTypes: [{ id: 1, name: 'Principal' }, { id: 2, name: 'Dessert' }, { id: 3, name: 'Drink' }],
        mappedMenus: [{ menuName: 'Hamburger', menuTypeId: 1 }, { menuName: 'Ice Cream', menuTypeId: 2 }, { menuName: 'Sprite', menuTypeId: 3 }]
    }
</script>

What I´m doing wrong?

like image 956
Andres Avatar asked Apr 14 '17 02:04

Andres


Video Answer


1 Answers

Shouldn't you use something like m.id instead of e.menuTypeId? Because the e.menuTypeId is also a model.

I've also tested binding in for and it works fine.

<select v-model="testVal">
    <option v-for="item in test" :value="item">{{item}}</option>
</select>
data() {
    return{
        test: ['one', 'two', 'three'],
        testVal: null
    }
}
like image 57
Dominik Dosoudil Avatar answered Oct 06 '22 00:10

Dominik Dosoudil