Dropdown elements in Vue.js

Łukasz Florczak
florczak.dev
Published in
2 min readJun 17, 2017

For everyone who has used jQuery for a long time it can be a bit difficult to do some – even if they look simple and basic – things using Vue and vanilla JavaScript only.

Dropdown elements are one of those things and they are very useful in a lot of parts of any website – menu, sidebars, faq etc.

Let’s create them and power them by Vue.

Template – HTML code

Our dropdown element consists of a container block – .dropdown and two child elements inside: .dropdown__header and .dropdown__content.

In a dropdown header I put in two Font Awesome Icons but it’s optional of course. The most important part of the dropdown header is a click action that starts toggleDropdown() method with $event parameter.

Styles – SCSS/CSS code

In the above snippet you can see that the dropdown header will receive is-active class. It’ll make (with + selector) the content element appear and also the icon will change.

Script – JS code

The last part is our method – toggleDropdown (). When a user clicks .dropdown__header element, we run toggleDropdown action and we check what DOM element was clicked – it is located in event.currentTarget.

It’s important that when we use currentTarget it doesn’t matter whether the user clicked on text, span element, blank space or icon i. currentTarget in this case is always the .dropdown__header. We can treat it as an equivalent of

$('.dropdown__header').click(function () { 
$(this).toggleClass('is-active');
}

in jQuery.

In our template we can of course have a lot of dropdowns. Because we add $event parameter to the click method, we always toggle the correct one.

I hope this short example will helpful to you. If you have any questions or any objections to the content, feel free to comment! If you like it – click the heart!

--

--