8

I need to use v-for with v-model. I read the docs and there is no example of how to use it with v-for without performing mutation outside the mutation handler.

How can I use v-model inside v-for without mutating the property directly?

  <div v-for="product in products">
     <select @change="addItem(product)" v-model="product.quantity">
        <option value="">0</option>
        <option v-for="n in 10">{{n}}</option>
      </select>
  </div>

 // component

  methods : {
    ...mapMutations({
      addToCart: ADD_TO_CART
    })
  },
4
  • What is the error you are getting with this, possible to create fiddle of it? Commented Dec 1, 2016 at 14:51
  • Do not mutate vuex store state outside mutation handlers Commented Dec 1, 2016 at 14:52
  • No, you can only change vex state with mutations only. Commented Dec 1, 2016 at 14:53
  • So how can I do this with v-for? Commented Dec 1, 2016 at 14:55

1 Answer 1

9

Not sure I completely understood what you're asking but have a look at the below:

EDIT

Updated to use Vuex - but not via v-model as that wouldn't be calling a mutation or action which is required

const store = new Vuex.Store({
    state: {
        products: [
        	{
                name: 'foo',
                quantity: 0,
            }, 
            {
                name: 'bar',
                quantity: 0,
        	},
        ],
    },
    getters: {
    	cart (state) {
        	return state.products.filter((product) => {
            	return product.quantity > 0
            })
        },    
    },
    mutations: {
        updateQuantity(state, payload) {
            state.products[payload.index].quantity = payload.val
        },
    }
})

new Vue({
    el: '#app',
    computed: {
        products() {
            return store.state.products
        },
        cart() {
            return store.getters.cart
        },
    },
    methods: {
        addItem (index, val) {
            store.commit('updateQuantity', { index, val })
        },
    }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@next"></script>
<div id="app">
    <div v-for="(product, index) in products">
        <label>{{ product.name }}</label>
        <select @change="addItem(index, $event.target.value)">
            <option value="">0</option>
            <option v-for="n in 10">{{n}}</option>
        </select>
    </div>
    <h1>cart</h1>
    <pre>{{ cart }}</pre>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.