Not sure what you call them, toggles or switches, but here's how you make a toggle button with Tailwindcss and Vue.
Let's make a new component called toggle.vue
and add the below code
<template>
<div
class="w-14 h-8 flex items-center bg-gray-300 rounded-full p-1 duration-300 cursor-pointer"
:class="{ 'bg-green-500': value }"
:aria-checked="value.toString()"
@click="toggle"
>
<div
class="bg-white w-6 h-6 rounded-full shadow-md transform duration-300"
:class="{ 'translate-x-6': value }"
></div>
</div>
</template>
<script>
export default {
props: {
value: {
type: Boolean,
default: false,
},
},
methods: {
toggle() {
this.$emit('input', !this.value)
}
}
};
</script>
Now, use the component in your code, whoever you'd like to.
<template>
<div>
<toggle v-model="toggleValue" />
</div>
</template>
<script>
export default {
data() {
return {
toggleValue: false,
};
},
};
</script>
Let's break down the component and try to understand.
Sorry for the bad image quality, not sure why is dev reducing the quality, even if it's hosted somewhere else, here's the link to a higher resolution pic
An outer which acts as a container for our toggle button, styled with rounded corners, and
display: flex
properties.Here's the thing when we want to add
v-model
to custom events, there are two important things involved, a prop named value and a event named input to emit. so technically you custom component should look like this.
<custom-component :value="variable" @input="doSomething"/>
The interesting thing is v-model
directive is a shorthand for the above attributes, which would make our component markup like this.
<custom-component v-model="variable"/>
That is exactly what we're doing here with our toggle component.
3.. Add a rounded div and bind this class to it translate-x-6
so it is gets slided to the right when value === true
:class="{ 'translate-x-6': value }"
4.. The final thing, just add a receive a prop with name value
, which is very important that it be named value.
We now have a working custom toggle component. Just call it wherever you need like below.
Here's a demo if you'd like to test it and here's the source code
Shameless plug, do follow me on twitter for more articles and announcements
Top comments (5)
Great tutorial Fayaz, congratulations for publishing it
Cool
Just Wow!
Glad you liked it!
Love your articles!