快速提问。如果我将data
放在数组形式的元素中,如下所示:
data: {
product: socks,
variants: [
{
variantId: 2234,
variantColor: 'Green',
variantQuantity: 0,
},
{
variantId: 2235,
variantColor: 'Blue',
variantQuantity: 10,
}
}
如何根据我将鼠标悬停在某个div上来选择某个variantQuantity?
完整代码:
HTML:
<div class="product-image">
<img :src="image" />
</div>
<div class="product-info">
<h1>{{ product }}</h1>
<p v-if="inStock">In Stock</p>
<p v-else :class="{ outOfStock: !inStock }">Out of Stock</p>
<ul>
<li v-for="detail in details">{{ detail }}</li>
</ul>
<div class="color-box"
v-for="variant in variants"
:key="variant.variantId"
:style="{ backgroundColor: variant.variantColor }"
@mouseover="updateProduct(variant.variantImage)"
>
</div>
<button v-on:click="addToCart"
:disabled="!inStock"
:class="{ disabledButton: !inStock }"
>
Add to cart
</button>
<div class="cart">
<p>Cart({{ cart }})</p>
</div>
</div>
Javascript:
var app = new Vue({
el: '#app',
data: {
product: 'Socks',
image: 'https://dl.dropboxusercontent.com/s/9zccs3f0pimj0wj/vmSocks-green-onWhite.jpg?dl=0',
inStock: false,
details: ['80% cotton', '20% polyester', 'Gender-neutral'],
variants: [
{
variantId: 2234,
variantColor: 'green',
variantImage: 'https://dl.dropboxusercontent.com/s/9zccs3f0pimj0wj/vmSocks-green-onWhite.jpg?dl=0',
variantQuantity: 0
},
{
variantId: 2235,
variantColor: 'blue',
variantImage: 'https://dl.dropboxusercontent.com/s/t32hpz32y7snfna/vmSocks-blue-onWhite.jpg?dl=0',
variantQuantity: 10
}
],
cart: 0
},
methods: {
addToCart() {
this.cart += 1
},
updateProduct(variantImage) {
this.image = variantImage
}
}
})
答案 0 :(得分:1)
您可以在variant.variantQuantity
事件处理程序表达式中包含mouseover
:
<div v-for="variant in variants"
@mouseover="updateProduct(variant.variantImage, variant.variantQuantity)"
>
还为数量添加数据属性,并更新处理程序以适应新属性:
data() {
return {
quantity: 0,
// ...
};
},
methods: {
updateProduct(variantImage, variantQuantity) {
this.image = variantImage;
this.quantity = variantQuantity;
},
// ...
}