Search code examples
vue.jsvuejs2vuex

Vue: Reacting to input change on array of inputs in v-for


I have an array of values I am setting the initial data value list to. I am using that list to render the values of the array in inputs. I am rendering the value of the input in a v-for using: <input :value="element" />. I tried using v-model but I get the error:

<input v-model="element">: You are binding v-model directly to a v-for iteration alias. This will not be able to modify the v-for source array because writing to the alias is like modifying a function local variable. Consider using an array of objects and use v-model on an object property instead.
    data() {
        let sizeFilterArray = this.$store.getters['main/getSizeFilters'];
        return {
            list: sizeFilterArray,
        }
    },

<draggable v-model="list">
   <div v-for="(element,index) in list" :key="index">
        <div class="element-box">
            <div class="element-input">
                <input :value="element" />
            </div>
        </div>
   </div>
</draggable>

Solution

  • The error is directing you to use an array of objects instead of values. So, you could modify to:

    <draggable v-model="list">
       <div v-for="item in list" :key="item.id">
            <div class="element-box">
                <div class="element-input">
                    <input v-model="item.value" />
                </div>
            </div>
       </div>
    </draggable>
    

    This assumes your sizeFilterArray is an array of objects like { id: 1, value: someValue }.