[Vuejs]-Can I send more than only value with v-model to v-for

0๐Ÿ‘

โœ…

You would want to create an object with the data you need for the product. Then you can use v-for to loop through and display them the way youโ€™d like.

In the example, I included a computed function that automatically returns the ones that get checked. This is done by v-model binding the checkbox to a flag inside your object. In this example, I called it selected, for simplicity.

var appvue = new Vue({
  el: '#appvue',
  data: {
    products: [{
      id: 1260,
      brand: "Brand A",
      product: "Bubblegun",
      image: "https://picsum.photos/100/100",
      selected: false
    }, {
      id: 1261,
      brand: "Brand B",
      product: "Bubblegum",
      image: "https://picsum.photos/100/100",
      selected: false
    }],
  },
  computed: {
    selectedProd() {
      return this.products.map(product => {
        if (product.selected) return product
      })
    }
  }

})
body {
  background: #20262E;
}

.form-row {
  width: 24%;
  display: inline-block;
}

#appvue {
  background: #fff;
  padding: 10px;
}

#prod_adjust {
  margin-top: 20px;
  background: #eee
}
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js"></script>

<div class="prod-wrap" id="appvue">
  <div class="form-row" v-for="product in products">
    <input v-model="product.selected" name="product-1260" id="product-1260" type="checkbox">
    <label for="product-1260">
		  <div class="thumb">
				<img :src="product.image">
			</div>
      <div class="details">
				<span class="brand">{{product.brand}}</span>
				<span class="product-title">{{product.product}}</span>
			</div>
		</label>
  </div>

  <div id="prod_adjust">
    <p v-for="product in selectedProd">{{product}}</p>
  </div>
</div>

0๐Ÿ‘

If you have the input as a JSON which has all the properties you are asking for (product_ID, img src, brand name) then you can assign the object to v-model instead of product_ID.

Your JSON array should look like this,

productsArray: [
{ productID: 1260,
product-title: "Product 1",
brand: "Brand 1",
img: "https://picsum.photos/100/100"
},
{ productID: 1261,
product-title: "Product 2",
brand: "Brand 2",
img: "https://picsum.photos/100/100"
},]

Then inside v-for you can read each object and when selected you can assign the entire object into selectedProd

0๐Ÿ‘

I used next way finally

    vueproducts = function(){
    appvue.selectedProd = [];
    var tempprod = {};
    $('.form-row input').each(function(){
        if ($(this).is(":checked")){
            tempprod.id = $(this).val();
            tempprod.img = $(this).parent().find('img').attr('src');
            tempprod.title = $(this).parent().find('.product-title').html();

            appvue.selectedProd.push(tempprod);
            tempprod = {};
        };
    });
}

Leave a comment