[Vuejs]-Vue button with 3-way toggle based on array value

1๐Ÿ‘

โœ…

You can use a computed property to extend the property on the data object, or you could do this is the mounted method. A computed property will be better as it will change when the data object does.

new Vue({
  el: '#app',
  computed: {
    formattedSubItems() {
      return this.subItems.map(si => {
        if (si.status === 'A') {
          return { ...si,
            text: 'Accept',
            class: 'accept'
          }

        } else if (si.status === 'B') {
          return { ...si,
            text: 'Pause',
            class: 'pause'
          }


        } else if (si.status === 'C') {
          return { ...si,
            text: 'Resume',
            class: 'resume'
          }

        }
      })
    }
  },
  data() {
    return {
      subItems: [{
          id: 123,
          status: 'A'
        },
        {
          id: 234,
          status: 'B'
        }
      ],
    }
  }
})
.accept {
  color: green
}

.pause {
  color: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div class="row" v-for="(subItem, key) in formattedSubItems" v-cloak>
    <button class="btn btn-block" :class="subItem.class" :style="{ border:none, borderRadius: .15 }" v-on:click="pause(subItem)" type="button" role="button" id="" aria-expanded="false">
        {{ subItem.text}}
    </button>
  </div>
</div>
๐Ÿ‘คGeorge

0๐Ÿ‘

You could also create a button object that contain your button name with based on your key. Like below example

buttons: {
   A: 'Accept',
   B: 'Pause',
   C: 'Resume'
}

And this buttons object you can use when you looping your subItems.

Please check below working code snippet.

new Vue({
  el: '#app',
  methods: {
    getClass(subItem) {
      return this.buttons[subItem.status].toLocaleLowerCase();
    },
    pause(subItem) {
      console.log(this.buttons[subItem.status])
    }
  },
  data() {
    return {
      subItems: [{
        id: 123,
        status: 'A'
      }, {
        id: 234,
        status: 'B'
      }, {
        id: 235,
        status: 'C'
      }],
      buttons: {
        A: 'Accept',
        B: 'Pause',
        C: 'Resume'
      }
    }
  }
})
.accept {
  color: green
}

.pause {
  color: violet
}

.resume {
  color: red
}

.btn-block {
  cursor: pointer;
  border: 1px solid;
  padding: 5px 10px;
  margin: 10px;
  font-size: 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div class="row" v-for="(subItem, key) in subItems">
    <button class="btn btn-block" :class="getClass(subItem)" @click="pause(subItem)" role="button" aria-expanded="false">
        {{ buttons[subItem.status]}}
    </button>
  </div>
</div>
๐Ÿ‘คNarendra Jadhav

Leave a comment