0

I have a local state that changes the chip icon and color on click, however, this event triggers a change in all the chips simultaneously.

I need the user to be able to select a single chip or multiple chips.

        const chipState = reactive({
            icon: addOutline,
            color: 'tertiary',
        })

        const selectService =  () => {
            if(chipState.icon == addOutline) {
                chipState.icon = checkmark;
                chipState.color = 'success';
            } else {
                chipState.icon = addOutline;
                chipState.color = 'tertiary';
            }
        }

        return { selectService,  ...toRefs(chipState) }
<ion-chip :color="color" @click="selectService"
          v-for="s of service.services" :key="s.id">
  <ion-label>{{s.name}}</ion-label>
  <ion-icon :icon="icon"></ion-icon>
</ion-chip>

EDIT

I made icon and color mutable by converting them to arrays, so chipState now looks like this:

const chipState = reactive({
    icon: [addOutline],
    color: ['tertiary']
})

This makes it possible to reference the index of each chip. The selectService function now looks like this:

  const selectService =  (i) => {
       if(chipState.icon[i] == addOutline) {
            chipState.icon[i] = checkmark;
             chipState.color[i] = 'success';
        } else {
             chipState.icon[i] = addOutline;
             chipState.color[i] = 'tertiary';
        }
   }

And the template:

 <ion-chip :color="color[index]" @click="selectService(index)"     
    v-for="(s, index) of service.services" :key="index">
  <ion-label>{{s.name}}</ion-label>
  <ion-icon :icon="icon[index]"></ion-icon>
 </ion-chip>

The "solution" posses a new problem: I'll have to hard-code the state of every item in the icon and color array for it to be effective.

carlhandy
  • 315
  • 1
  • 8
  • 22
  • it would be a lot easier to support you if there was a sample project in codepen or someplace – Aaron Saunders May 17 '21 at 15:00
  • @AaronSaunders here's the sample project https://github.com/carlHandy/Ionic5-Event-Bus. It also replicates this issue: https://stackoverflow.com/questions/67672440/unable-to-listen-to-emitted-events-with-ionic-5 – carlhandy May 24 '21 at 18:22

0 Answers0