In my Vue app: I'm using v-for to render product divs, each of which with a pair of buttons, 'new' and 'used', and I want to add 'active' class when a button is clicked. Problem is that I'm adding 'active' class to either all 'new' buttons or all 'used' buttons; pretty sure there's a Vue way to do this, other than getting the index of the clicked button and setting class to corresponding el. What am I missing?
markup:
<div id="app">
<div class="products">
<div class="product" v-for="product in products" :key="product.productID">
<div class="product-image">
<img :src=product.imgDef :alt="product.name" v-bind:title="product.name" />
</div>
<div class="product-summary">
<p>{{ product.name }}</p>
<p>{{ product.info }}</p>
<ul>
<li v-for="detail in product.details">{{ detail }}</li>
</ul>
<div
class="conditions"
v-for="variant in product.variants"
v-bind:key="variant.variantID"
v-bind:style="variant.variantStyleObj"
>
<!--
renders a 'new' button and a 'used' button in each div.product;
- clicking should add 'active' class only to clicked button
-->
<button
type="button"
v-on:click="updateProductImage(variant.variantImage, variant.variantID, product.productID, variant.condition)"
:class="[ 'condition', variant.condition, {active: conditionClass == variant.condition} ]"
>
{{ variant.condition }}
</button>
</div>
</div><!-- END .product-summary -->
</div><!-- END .product -->
</div><!-- END #app -->
js:
var app = new Vue({
el: '#app',
data: {
products: [
{
productID: 1,
name: "",
info: "",
imgDef: "../../images-dev/...jpg",
details: [],
inStock: false,
variants: [
{
variantID: "123",
variantImage: "../../images-dev/1a.jpg",
condition: "new"
},
{
variantID: "321",
variantImage: "../../images-dev/1b.jpg",
condition: "used"
}
],
inventory: 9
},
cart: 0,
// conditionClass: ""
},
methods: {
addToCart: function() {
this.cart += 3;
},
updateProductImage: function(variantImage, variantKey, productKey, variantCondition) {
this.products[productKey-1].imgDef = variantImage;
this.conditionClass = variantCondition;
}
}
})