[Vuejs]-Vue3 can't get dynamic styling to only apply to specific buttons

1👍

Maybe something like following snippet (if you need more buttons to be styled at once save selected in array, if only one just save selected):

const app = Vue.createApp({
  data() {
    return {
      genusList: [{label: 1}, {label: 2}, {label: 3}],
      selGenus: [],
    };
  },
  methods: {
    isSelected(selectedGenus) {
      return this.selGenus.includes(selectedGenus)
    },
    filterGenus(selectedGenus) {
      if (this.isSelected(selectedGenus)) {
        this.selGenus = this.selGenus.filter(s => s !== selectedGenus)
      } else {
        this.selGenus = [...this.selGenus, selectedGenus]
      }
      this.$emit('filter-genus', selectedGenus)
    },
    clearFilter() {
      this.selGenus = []
      this.$emit('clear-filter')
    }
  },
})
app.component('baseButton', {
  template: `<button :class="mode"><slot /></button>`,
  props: ['mode']
})
app.mount('#demo')
.outline {
  outline: 2px solid red;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <ul>
    <li v-for="genus of genusList" :key="genus.label">
      <base-button @click="filterGenus(genus.label)" 
                   :mode="isSelected(genus.label) ? 'outline' :''">
        {{ genus.label }}
      </base-button>
    </li>
    <base-button @click="clearFilter()" mode="flat">
      Clear Filter
    </base-button>
  </ul>
</div>

Leave a comment