Skip to content

My Vue Project v-model not working inside v-for loop

I have a problem that, v-model not working inside v-for Loop.

Inside my template

<li v-for="(data, key) in product.variants" :key="data.id">
   <input type="radio" :id="'variant' + key" name="Variant" v-model="cart.variantId"/>
   <label :for="'variant' + key">{{data.variant}}</label>
</li>

inside my script

data(){
   return{
     cart: {
         quantity: '1',
         colorId: '',
         variantId: '',
      },
   },

   computed: {
      // Get Quick View Product
      product(){
         return this.$store.state.quickViewProduct;
      },
   },

},

Now how I fix this problem

Answer

If you are storing a value from a set of radio. buttons in a property, you need to identify the buttons. Not with the id, but with a value. Try this:

<li v-for="(data, key) in product.variants" :key="data.id">
   <input type="radio" :id="'variant' + key" name="Variant" v-model="cart.variantId" :value="data.id"/>
   <label :for="'variant' + key">{{data.variant}}</label>
</li>