How to hide and show divs on button click created dynamically in vue.js?

by darrion.kuhn , in category: Javascript , 3 months ago

How to hide and show divs on button click created dynamically in vue.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 3 months ago

@darrion.kuhn 

To hide and show divs on button click that are created dynamically in Vue.js, you can follow these steps:

  1. Create a new Vue component that will handle the logic for showing and hiding the divs. This component will contain the array of divs that will be dynamically generated.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<template>
  <div>
    <div v-for="(element, index) in elements" :key="index" :class="{ 'hidden': !element.isVisible }">{{ element.content }}</div>
    <button @click="toggleDivs">Toggle Divs</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      elements: [
        { content: 'Div 1', isVisible: true },
        { content: 'Div 2', isVisible: true },
        { content: 'Div 3', isVisible: true }
      ]
    };
  },
  methods: {
    toggleDivs() {
      this.elements.forEach(element => {
        element.isVisible = !element.isVisible;
      });
    }
  }
};
</script>

<style>
.hidden {
  display: none;
}
</style>


  1. In the above code, we have a Vue component with an array of elements, each of which has a content property and an isVisible property that determines whether the div should be shown or hidden.
  2. We use v-for to loop through the elements and dynamically generate divs based on the array data. We also use the hidden class to hide divs that have isVisible set to false.
  3. We have a toggleDivs method that toggles the isVisible property of each element in the array when the "Toggle Divs" button is clicked.
  4. Finally, we use the @click directive to call the toggleDivs method when the button is clicked.


By following the above steps, you can create a Vue component that dynamically generates and shows/hides divs on button click.