[Vuejs]-Vue 3: Toggle class onclick of button inside v-for loop

1👍

First thing, the isActive is a boolean type that does not have any property inside it, so it is throwing the error, "Cannot read properties of undefined (reading 'value')". You need to make isActive an object so it can hold the indexes as properties. Also, you need to use the reactive API, so the changes on an index like isActive[i] will be reactive in the Vue template.

The script should look something like this-

<script setup>
import { reactive } from "vue"

const items = [{"details": "First"}, {"details": "Second"}];

const isActive = reactive({});

const toggleAccordion = async (i) => {
  isActive[i] = isActive[i] ? !isActive[i] : true;
}; 
</script>

Here is a working demo, try out.

2👍

Create activeMap ale toggle with index using toggleAccordion.

<script setup>
    const activeMap = reactive({})

    const toggleAccordion = (index) => {
        activeMap[index] = !activeMap[index]
    }
</script>

<template>
<div>
    <div v-for="(item, index) in items" :key="item.id">
        <div class="my-class" :class="{ 'is-open': !!activeMap[index] }" v-html="item.details">
        </div>
        <button @click="() => toggleAccordion(index)">Toggle text</button>
    </div>
</div>

Leave a comment