A Pen by Ryan Hightower on CodePen.
Created
January 17, 2021 00:37
-
-
Save ryanhightower/8886c1462131967a55b99d191c673c1d to your computer and use it in GitHub Desktop.
Vue 2 Toggle Switch Component with Variable Sizes
This file contains 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="switch"> | |
<input type="checkbox" @change="$emit('change', $event.target.checked)" id="switch" /> | |
<label | |
for="switch" | |
:style="cssVars" | |
>Toggle</label> | |
</div> | |
</template> | |
<script> | |
export default { | |
model: { | |
prop: 'checked', | |
event: 'change' | |
}, | |
props: { | |
checked: Boolean, | |
color: { | |
type: String, | |
default: "#E17165" | |
}, | |
size: { | |
type: String, | |
default: "20px" | |
}, | |
gutter: { | |
type: String, | |
default: "5px" | |
} | |
}, | |
data() { | |
return {}; | |
}, | |
computed: { | |
cssVars() { | |
return { | |
'--color': this.color, | |
'--size': this.size, | |
'--gutter': this.gutter, | |
} | |
} | |
}, | |
methods: { | |
onChange(e) { | |
this.$emit('change', e.target.value) | |
} | |
} | |
}; | |
</script> | |
<style lang="scss" scoped> | |
.switch { | |
display: inline-block; | |
input[type=checkbox]{ | |
height: 0; | |
width: 0; | |
visibility: hidden; | |
} | |
label { | |
cursor: pointer; | |
text-indent: -9999px; | |
width: calc( (var(--size) + var(--gutter) * 2) * 2 ); | |
height: calc(var(--size) + var(--gutter) * 2); | |
background: grey; | |
display: block; | |
border-radius: 100px; | |
position: relative; | |
} | |
label:after { | |
content: ''; | |
position: absolute; | |
top: var(--gutter); | |
left: var(--gutter); | |
width: var(--size); | |
height: var(--size); | |
background: #fff; | |
border-radius: var(--size); | |
transition: 0.3s; | |
} | |
input:checked + label { | |
background-color: var(--color); | |
} | |
// $test: $gutter/2; | |
input:checked + label:after { | |
left: calc(100% - var(--gutter)); | |
transform: translateX(-100%); | |
} | |
label:active:after { | |
width: calc( var(--size) * 1.4 ); | |
} | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment