Vue Collapsible Panel Component (with persisted state)

Today, ill create a simple re-usable collapsible panel component that saves state in localStorage.

Starting out

I start out by creating a basic vue project through the CLI (default settings)

Next up, add Fontawesome and Bulma (I ❤️ Bulma) yarn add bulma.

package.json after dependencies has been added

(I load in bulma through sass so I can override colors etc. so I’ve also installed node-sass and sass-loader as devDependencies)

In main.js I’ve added the basic FontAwesome setup (as per the link)

I just add ChevronUp (🔼) and ChevronDown (🔽) to the library and off we go.

On to the actual component

I’ve created the “panel” out of the bulma card component.
The component takes 2 props, namely id and title.
title is used for the card header and id is used for state management.

The component loads/saves the collapsible state in localStorage.

I’ve created a small extension to help (de)serialize objects to localStorage as localStorage only really does key/value pairs (which could have been used, but I find this to be much better).

We load the state during mounted() and we get/set via the following methods

The state is saved in an object in localStorage under the key collapsibles
and id‘s are added to that object with the collapsible state.
It creates something like this

Complete component

The component has 2 slots, a default one and a footer – you can see that in the usage below.


I’ve shown 2 usage scenarios in the following code. 1 with the footer and 1 without.

Below you can see the storage change when I change the state.

you can find the complete project on my github

Leave a Reply

Your email address will not be published. Required fields are marked *