How to create a reusable toggle switch component with Vue.js

Laurent Perrier
Jul 30, 2017 · 1 min read

The toggle switch we built in the previous video is only comprised of 4 elements and 4 lines of code, but it’s more than we’d like to type and remember every time we need a toggle switch.

What we’d like instead, is to have is a simple <toggle-switch> element we can use throughout our project. Much cleaner!

To do this, we will extract the markup needed for the toggle switch to a reusable Vue component. We will also add a little bit of functionality to the component so that v-model works like with native checkbox input elements, and so that we can set a default checked state .

Let’s get started!

In this example, I used a checkbox input in the component, but it’s not necessary. We could rewrite the template without the input, and instead toggle the “on” and “off” styling of the component based on the checked property through dynamic CSS classes.


Originally published at laurentperrier.ca.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade