Skip to content

Instantly share code, notes, and snippets.

@paulund
Created Apr 15, 2018
Embed
What would you like to do?
How to create a VueJS toggle component
<template>
<div class="my-2">
<div class="toggle">
<input type="checkbox" :id="id" :name="id" value="1" v-on:change="updateValue($event.target.value)" :checked="isChecked" />
<label :for="id"></label>
</div>
<p class="inline-block">{{ label }}</p>
</div>
</template>
<style lang="scss">
.toggle {
display: inline-block;
position: relative;
cursor: pointer;
height: 2rem;
width: 4rem;
background: #3490dc;
border-radius: 9999px;
margin-bottom: 1rem;
input[type=checkbox] {
visibility: hidden;
}
label {
display: block;
width: 22px;
height: 22px;
border-radius: 50%;
transition: all .5s ease;
cursor: pointer;
position: absolute;
top: 5px;
z-index: 1;
left: 7px;
background: #ddd;
}
input[type=checkbox]:checked + label {
left: 35px;
background: #FFF;
}
}
</style>
<script>
export default {
props: ['id', 'label', 'value'],
methods: {
updateValue: function () {
let value = 0
if(this.value === 0) {
value = 1
}
this.$emit('input', value)
}
},
computed: {
isChecked() {
return this.value === 1
}
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment