Skip to content

Instantly share code, notes, and snippets.

@paulund
Created April 15, 2018 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulund/45eb97a6d1ab1abaee9a53b57a3cb340 to your computer and use it in GitHub Desktop.
Save paulund/45eb97a6d1ab1abaee9a53b57a3cb340 to your computer and use it in GitHub Desktop.
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