It looks like you're trying to use the ref attribute within a v-for loop, which won't work as you might expect because ref inside a v-for will result in an array of elements being assigned to the ref, not a single element. However, in the Vue 3 Composition API with <script setup>, you need to use a function to access the refs when they are inside a loop.
Here's how you can modify your code to work with refs inside a v-for:
<template>
<div v-for="(value, index) in curQuestion.answers" :key="index"
:ref="el => { if (el) options[index] = el }"
class="neumorph-1 option option-default">
<div class="rounded-lg font-bold flex p-2" @click="scoreQuestion(index, value.score)">
<!-- option ID -->
<div class="p-3 rounded-lg">{{ index+1 }}</div>
<!-- option name -->
<div class="flex items-center pl-6">{{ value.answer }}</div>
</div>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue';
const curQuestion = reactive({
answers: [
// ... your answers here
]
});
const options = reactive({});
const score = ref(0);
const scoreQuestion = function(index, curScore) {
score.value = score.value + curQuestion.answers[index].score * curScore / 100;
const optionElement = options[index];
optionElement.classList.remove("option-default");
if (curScore > 0) {
optionElement.classList.add("option-correct");
} else {
optionElement.classList.add("option-wrong");
}
}
</script>
In this solution, we use a function :ref="el => { if (el) options[index] = el }" to assign the DOM element to the options object at the correct index. This way, each option element is stored in the options object, and you can access it using the index in your scoreQuestion function.
Please note that I've used reactive for options instead of ref because we are dealing with an object that will have multiple properties (one for each option element). Also, ensure that curQuestion.answers is properly reactive, so changes to it will be reflected in the template. If curQuestion is a prop or comes from a store, you might need to handle it differently.