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.
>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 }"
