[Vuejs]-How to use JSON/Object data to make a dynamic Menu/SideNav in Vue JS

1πŸ‘

βœ…

One way of dong this is:

  • add an extra property isOpen: false to every menu item

  • then toggle the isOpen property by adding a @click listener and passing the menu item as argument

    <div id="side-bar">
        <ul>
            <li v-for="item in menu">
                <div>
                    <h4 @click="toggleChildren(item)">{{item.name}}</h4>
                    <ul v-show="item.isOpen">
                        <li v-for="subItem in item.children">{{subItem.name}}</li>
                    </ul>
                </div>
            </li>
        </ul>
    </div>  
    

script

new Vue({
    el: '#side-bar',
    data:{
                menu:[
            {
                id: 1,
                name: 'Men',
                children: [{name: "Tops"}, {name: "Bottom"}],
                isOpen:false
            },
            {
                id: 2,
                name: 'Women',
                children: [{name: "Tops"}, {name: "Bottom"}],
                isOpen:false
            },
            {
                id: 3,
                name: 'Electronics',
                children: [{name: "Smart Phone"}, {name: "Feature Phone"}],
                isOpen:false
            }
        ] 

    },
    methods:{
        toggleChildren(item){
            item.isOpen = !item.isOpen
        }
    }

}); 

Here is the fiddle

πŸ‘€Vamsi Krishna

1πŸ‘

use v-for

var example1 = new Vue({
  el: '#example-1',      
  data: {
    items: [
      {
        id: 1,
        name: 'Men',
        show: false,
        children: [{name: "Tops"}, {name: "Bottom"}]
      },
      {
        id: 2,
        name: 'Women',
        show: false,
        children: [{name: "Tops"}, {name: "Bottom"}]
      },
      {
        id: 3,
        name: 'Electronics',
        show: false,
        children: [{name: "Smart Phone"}, {name: "Feature Phone"}]
      },
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.js"></script>

<ul id="example-1">
  <li v-for="item in items" >
    <button v-on:click="item.show = !item.show">
      {{item.name}}
    </button>
    <ul v-if="item.show">
      <li v-for="children in item.children">
        <button>
          {{children.name}}
        </button>
      </li>
    </ul>
  </li>
</ul>
πŸ‘€Behnam

Leave a comment