Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I change each number's background color?

I am dealing with a simple project but have a problem:

<script setup>
import { ref } from "vue";

const isActive = ref(false);
const rates = ref([1, 2, 3, 4, 5]);

const selectPick = () => {
  isActive.value = !isActive.value;
};
</script>
<template>
  <main>
    <div v-show="!isVisible" class="card-container">
      <div class="content-container">
      ...
        <ul>
          <li
            v-for="rate in rates"
            :key="rate"
            @click="selectPick"
            class="rating"
            :class="{ active: isActive }"
          >
            {{ rate }}
          </li>
        </ul>

        <button class="btn">Submit</button>
      </div>
    </div>
  </main>
</template>
  • My goal: When I click any number related button’s background color should change to orange but if I click another, it must return the old paint.
  • Problem: When I click any number all number’s background color return orange.

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Define ref variable and change it value on @click event, setting clicked btn value. Then compare btn value with variable for custom styling.

Try this.

<template>
  <main>
    <div v-show="!isVisible" class="card-container">
      <div class="content-container">
      ...
        <ul>
          <li
            v-for="rate in rates"
            :key="rate"
            @click="activeRef = rate"
            class="rating"
            :class="{ active: activeRef === rate }"
          >
            {{ rate }}
          </li>
        </ul>

        <button class="btn">Submit</button>
      </div>
    </div>
  </main>
</template>

<script setup>
import { ref } from "vue";

const activeRef = ref(null);
const rates = ref([1, 2, 3, 4, 5]);
</script>

Main changes in:

const activeRef = ref(null);

And

@click="activeRef = rate"
...
:class="{ active: activeRef === rate }"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading