Boris
Boris

Reputation: 105

Toggle MANY divs onclick in Vue without pre-declaring the variables

I have many elements (around 30) to toggle (hide/show) on click. I use the v-show directive, but I need to declare all the variables name beforehand. If I don't declare them, the v-show doesn't work. This is not practical because every time the elements change I would have to change them in the template and in the list.

Is there a way to achieve this in Vue without pre-declaring the variables, or I'll have to do something like in this answer in pure JavaScript Toggling many div id ?

Upvotes: 0

Views: 593

Answers (2)

Radu Diță
Radu Diță

Reputation: 14171

You can achieve this if you generate the variables programatically

data() {
 return {
  items: [...Array(30).keys()].map(i => ({ id: i, isActive: true }))
 };
}

This will generate an object with 30 entries that have an id and a flag regarding active status.

You can now v-for over them and handle the click based on the id

<div
  v-for="item in items"
  :key="item.index"
  v-show="item.isActive"
  @click="handleClick(item)"
>{{item.id}}</div>

And finally the handleClick method

methods: {
 handleClick(item) {
  item.isActive = false;
 }
},

A working example can be found here

Upvotes: 2

stasera
stasera

Reputation: 96

if you have to show 30 divs simultaneously you can do this.

<template>
    <div>
        <a @click="!isActive">Toggle to Show Divs</a> <-- At click, isActive = !isActive -->
        <div id="1" v-if="isActive"></div> <!-- Show when isActive = true -->
        <div id="2" v-if="isActive"></div> 
        <div id="3" v-if="isActive"></div> 
        <div id="4" v-if="isActive"></div> 
        <div id="5" v-if="isActive"></div> 
        <div id="6" v-if="isActive"></div> 
        ...
    </div>
</template>

<script>
    export default {
        data() {
            return {
                isActive: false
            }
        },
    }
</script>

The only variable will be isActive

Upvotes: -1

Related Questions