Home > Net >  style and work with arr in vue.js. How styling only active element?
style and work with arr in vue.js. How styling only active element?

Time:10-10

I have cards array and button on every card. If I click my button, all buttons are changing style.

How apply style to active button not for all?

<template>
  <div>
    <div v-for="i in cards" id="card" :key="i" >
      <btn
        id="heartBtn"
        
        aria-hidden="true"
        :
        @click="changeColor = !changeColor"
      ></btn>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MainLayout',
  data: () => ({
    changeColor: false,
    cards: [1, 2, 3, 4, 5, 6, 7, 8, 10, 11],
  }),
  computed: {
    color() {
      if (this.changeColor === true) {
        return 'faClick'
      } else {
        return 'fa'
      }
    },
  },
}
</script>

CodePudding user response:

tnx for help All/ I take you code and rebuild his.I got the right one code for me/ Rebild code:

            id="card"
            
            v-for="card in cards"
            :key="card.id"
            ><btn
            id="heartBtn"
            
            aria-hidden="true"
            :
            @click="changeColor(card.id)"
            ></btn>
        </div>
    </div>
        </div>
    </div>
</template>
<script>
export default {
  name: 'mainLayout',
  data: () => ({
    cards: [
      { id: 1, color: false },
      { id: 2, color: false },
      { id: 3, color: false },
      { id: 4, color: false }
    ]
  }),
  methods: {
    changeColor (id) {
      this.cards = this.cards.map((card) => {
        if (card.id === id) {
          card.color = !card.color
        }
        return card
      })
    }
  },```

CodePudding user response:

Something like this will solve your issue

<template>
  <div>
    <div
      v-for="card in cards"
      :key="card.id"
      
      :
    >
      <button
        id="heartBtn"
        
        aria-hidden="true"
        @click="toggleColor(card.id)"
      >
        {{ card.id }}
      </button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MainLayout',
  data() {
    return {
      cards: [
        { id: 1, color: false },
        { id: 2, color: false },
        { id: 3, color: false },
        { id: 4, color: false },
      ],
    }
  },
  methods: {
    toggleColor(id) {
      this.cards = this.cards.map((card) => {
        if (card.id === id) {
          card.color = !card.color
        }
        return card
      })
    },
  },
}
</script>

<style scoped>
.faClick { /* this is a visual example */
  border: 2px solid red;
}
</style>

Here is how it looks in the DOM

enter image description here

And regarding the state

enter image description here

  • Related