[Vue.js] Accordion (Collapsible Content)


Accordion (collapsible content) implementation via Vue.js. The accordion here is similar to the accordion example in Bootstrap Collapse. Click the following panels to see the demo.

Title #1
Content Body #1
Title #2
Content Body #2
Title #3
Content Body #3

The following is the source code for above demo.

HTML:

<div id="vueapp">

<div class="panel">
  <div class="panel-title" v-on:click="sel == 1 ? sel = 0 : sel = 1">
    Title #1
  </div>
  <div class="panel-body" v-show="sel == 1">
    Content Body #1
  </div>
</div>
<div class="panel">
  <div class="panel-title" v-on:click="sel == 2 ? sel = 0 : sel = 2">
    Title #2
  </div>
  <div class="panel-body" v-show="sel == 2">
    Content Body #2
  </div>
</div>
<div class="panel">
  <div class="panel-title" v-on:click="sel == 3 ? sel = 0 : sel = 3">
    Title #3
  </div>
  <div class="panel-body" v-show="sel == 3">
    Content Body #3
  </div>
</div>

</div>

<script src="https://unpkg.com/vue@2.3.3/dist/vue.js"></script>

We use the variable sel to indicate which panel is opened. If the value of sel is 0, all panels are collapsed. If 1, the first panel is opened, and so on.

JavaScript:

'use strict';

var app = new Vue({
  el: '#vueapp',
  data: {
    sel: 0
  }
});

Set sel to 0 in the initialization phase to make all panles collapsed.

CSS:

.panel {
  margin-bottom: 1rem;
  border: 1px solid #ccc;
}
.panel-title {
  font-weight: bold;
  background-color: #ccc;
  padding: 0.01em 16px;
  cursor: pointer;
}
.panel-body {
  padding: 0.01em 16px;
}

Nothing special in CSS code here. For demo purpose, I make CSS very simple. You can try to add some animation if you want.


Tested on:

  • Chromium Version 58.0.3029.110 Built on Ubuntu , running on Ubuntu 17.04 (64-bit)
  • Vue.js 2.3.3

References:

[1]
[2]How To Create an Accordion - W3Schools