Search code examples
javascriptarraysvue.jsvuejs2vue-component

Dynamically adding counter to v-data-table with two buttons to increment and decrement and the number between them


The problem here is I am getting data from an api and the data has no property like 'count' so I need to create another array and use it in v-for.

But I want to specify a number with the counter and when the add button is clicked on each row, I want to add that object to a vuex state equal to the number in the counter.

Now when i click to the increment button all columns of counts are incrementing at the same time on all rows.

Also this button is in a different component and the count value will be dynamically passed to this component.

I tried to add td's to all rows but its incrementing in every single column.

Thanks in advance.

Here is the v-data-table:

<v-data-table dense :headers="dataTableHeaders" :items="filteredCoins" :items-per-page="5">

        <template v-slot:body="{ items }">
          <tbody>
            <tr v-for="coin in items" :key="coin.symbol">
              <td>{{ coin.symbol }}</td>
              <td>{{ coin.lastPrice }}</td>
              <td>
                <v-btn icon x-small text @click.stop="counter++">
                  <v-icon>mdi-arrow-up</v-icon>
                </v-btn>
                <v-counter :value="counter" />
                <v-btn icon x-small text @click.stop="counter--">
                  <v-icon>mdi-arrow-down</v-icon>
                </v-btn>
              </td>
              <td v-if="$store.state.portfolio.includes(coin)">
                <UpdateDeleteButtons :selected-coin="coin" :count="counter"/>
              </td>
              <td v-else>
                <AddButton :selected-coin="coin" :count="counter"/>
              </td>
            </tr>
          </tbody>
        </template>

      </v-data-table>

And here is the AddButton component:

<template>
  <v-btn x-small color="#0EDC79" @click="saveCoinToPortfolio()">
    Portfolyonuza Ekleyin
  </v-btn>
</template>

<script>
import { mapActions } from 'vuex';
export default {
  props: {
    selectedCoin: [],
    count: {
      type: Number,
      default: 1
    }
  },

  name: 'AddButton',

  methods: {
    ...mapActions(['saveCoinToPortfolio']),

    saveCoinToPortfolio() {
      this.$store.dispatch('saveCoinToPortfolio', {data: this.selectedCoin, count: this.count})
    }
  }
}
</script>

Solution

  • Looks like you have only one counter variable, which is used in all rows. Try adding the counter to your coin data, or if you do not want to change those, add a separate coinCounter object which stores counter by coin key (coin.symbol). It should look something like this:

    <v-btn icon x-small text @click.stop="coinCounter[coin.symbol]++">...
    

    or

    <v-btn icon x-small text @click.stop="coin.counter++">...