Created
April 15, 2018 14:25
-
-
Save paulund/45eb97a6d1ab1abaee9a53b57a3cb340 to your computer and use it in GitHub Desktop.
How to create a VueJS toggle component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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