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

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.