Vue JS - Bind select option value to model inside

2020-06-04 03:29发布

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?

标签: vuejs2
1条回答
干净又极端
2楼-- · 2020-06-04 04:03

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
    }
}
查看更多
登录 后发表回答