Home > Blockchain >  Handling button in multiple Cards
Handling button in multiple Cards

Time:10-28

I've product listing page where I use multiple ProductCard component. I need to add Spinner to Add to cart button when clicking on it, but if I just add Spinner to v-else I've Spinners in every ProductCard. How to control only this ProductCard where I click Add to cart button?

Parent's component:

<ProductCard
  v-for="product in products"
  :key="product.id"
  :product="product"
/>

Child's component:

<template>
  <div id="productCart">
    <div>
      <NuxtLink :to="`/product/${item.slug}`" />
      <NuxtLink v-if="item.name" :to="`/product/${item.slug}`">
        <h5
          id="productName"
          v-text="item.name"
        />
      </NuxtLink>
      <Button
        v-if="!loading"
        @click="addToBuyCart({ product: item })"
        v-text="$t('labels.buy')"
      />
      <Spinner v-else />
    </div>
  </div>
</template>

loading is defined in composable, and it's updating in addToBuyCart function by making it true, then adding to cart (api), then making it false

CodePudding user response:

As pointed by IVO, in such situations you should check against a value specific for each item in the loop, item ID for example, instead of a boolean which lacks specificity and therefore cannot be used for such scenarios.

<template>
  <div id="productCart">
    <div>
      <NuxtLink :to="`/product/${item.slug}`" />
      <NuxtLink v-if="item.name" :to="`/product/${item.slug}`">
        <h5
          id="productName"
          v-text="item.name"
        />
      </NuxtLink>
      <Button
        v-if="loading !== item.id"
        @click="addToBuyCart({ product: item })"
        v-text="$t('labels.buy')"
      />
      <Spinner v-else />
    </div>
  </div>
</template>

const addToBuyCart = ({product}) => {
  loading = product.id
  // some logic or request
  loading = null
}
  • Related