Search code examples
javascriptvue.jsvuejs2vue-componentvuetify.js

Use Vuetify v-btn with loader inside a v-for loop


I am trying to figure out how to have my dynamically generated buttons inside a for loop each have a separate loader. Vuetify has buttons with Loaders.

The problem I am having is, When these buttons are in a for loop and one is clicked they all show the loading indicator. I would like only the one that is clicked to show the loading indicator.

HTML:

<div v-for="(item, i) in items" :key='i'>

<v-btn 
dark 
color="pink"
:loading="loading"
@click="loader = 'loading'"
>
  <v-icon>location_on</v-icon> Lookup
  <span slot="loader">locating...</span>
  <span slot="loader" class="custom-loader">
      <v-icon dark>cached</v-icon>
  </span>
</v-btn>

</div>

SCRIPT

data () {
      return {
        loader: null,
        loading: false
      }
    },

Let's say I have 3 items. The code above will generate three buttons but they all will share the same loading param. How can I have each button use its only loading param? As always any and all help is much appreciated.


Solution

  • You're using the same data property for all buttons, so these buttons share the same loading state which affects the at one time, to make difference try to add a data property called index which represents the current clicked button index :

    data () {
          return {
            index:-1,
            loader: null,
            loading: false
          }
        },
    

    and bind loading prop to the condition loading && i==index and update the current index on click event @click="loader = 'loading';index=i" :

    <div v-for="(item, i) in items" :key='i'>
    
    <v-btn 
    dark 
    color="pink"
    :loading="loading && i==index"
    @click="loader = 'loading';index=i"
    >
      <v-icon>location_on</v-icon> Lookup
      <span slot="loader">locating...</span>
      <span slot="loader" class="custom-loader">
          <v-icon dark>cached</v-icon>
      </span>
    </v-btn>
    
    </div>