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

2๐Ÿ‘

โœ…

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

-1๐Ÿ‘

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

๐Ÿ‘คstasera

Leave a comment