Search code examples
vue.jsvuejs2vue-componentvuexvuetify.js

How to hide and show divs on button click created dynamically in Vuejs


I have dynamically created buttons and divs, I want to show div on click of associated button and hide the rest. I don't know the count as they are creating dynamically. How to do it in vue js?

<div style="margin-left: -88px;margin-top: 20px;">

<button v-for="namelock in tour_location"  style="background-color:#EFF5FA;border: 0;border-radius: 15px;font-size: 14px;margin-left: 60px;">{{namelock.name}}</button>



<div v-for="(location,index ) in tour_location">

<h1>My Dynamic data</h1></div>

Solution

  • You can use v-show, change the show prop @click into an id of the object you want to show then on v-show you can check if the show prop is equal to the object id that you want to show

    <div id="app">
      <button v-for="b in buttons" @click='show = b' class="btn m-4 btn-primary">{{b}}</button>
      <div class="container">
        <div class="row">
          <div v-show="show === d.id" v-for='d in divs' class="col-sm-3 m-2">
            {{d.name}}
          </div>
        </div>
      </div>
    </div>
    

    Then in vue script

    var app = new Vue({
      el: '#app',
      data: {
        buttons: [1,2,3],
        divs: [{id:1,name:'apple'},{id:2,name:'mango'},{id:3,name:'banana'}],
        show: null
      },
    })
    

    Heres the working code in the Code pen