Don Chan
Don Chan

Reputation: 61

How to conditionally disable a button in Vue v-for loop

I have the following code, every time the condition is true, the disabled is affecting all of the buttons in all the items.

I have searched and couldn't find the proper way of doing it, can someone shed some light please?

The purpose of this is to limit the number of an item that the user can add to the shopping basket by disabling the + button.

            <tbody v-for="(item, index) in getMenuItems" :key="index">
                <tr>
                    <td><strong>{{ item.name }}</strong></td>
                </tr>
                <tr v-for="(option, index) in item.options" :key="index" >
                    <td>{{ option.size }}</td>
                    <td>{{ option.price}}</td>
                    <td >
                        <button 
                            class="btn btn-sm btn-outline-success"
                            type="button"
                            @click="addToBasket( item, option)"
                            :disabled="itemdisabled=='disabled'"
                        >+</button>
                    </td>
                        {{ basket }}
                </tr>
            </tbody>

Upvotes: 6

Views: 5177

Answers (1)

ittus
ittus

Reputation: 22403

You can use computed or methods to check disabled.

For example:

<tbody v-for="(item, index) in getMenuItems" :key="index">
  <tr>
      <td><strong>{{ item.name }}</strong></td>
  </tr>
  <tr v-for="(option, index) in item.options" :key="index" >
      <td>{{ option.size }}</td>
      <td>{{ option.price}}</td>
      <td >
          <button 
              class="btn btn-sm btn-outline-success"
              type="button"
              @click="addToBasket( item, option)"
              :disabled="isDisable(option, index)"
          >+</button>
      </td>
          {{ basket }}
  </tr>
</tbody>

<script>
  export default {
    ...
    methods: {
      isDisable(option, index) {
        // check option and index
        // return true - disable, false - active
      }
    }
  }
</script>

Upvotes: 7

Related Questions