Skip to content

Instantly share code, notes, and snippets.

@Jonarod
Created November 23, 2019 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Jonarod/b2669a2314385cffe5f84211a6a11e13 to your computer and use it in GitHub Desktop.
Save Jonarod/b2669a2314385cffe5f84211a6a11e13 to your computer and use it in GitHub Desktop.
Simple custom Toggle Switch button for Vue.js, compatible with v-model.
/**
* @usage:
*
* <ToggleSwitch :trueFalseLabels="['On','Off']" :trueFalseColors="['#1CD4A7','#ccc']" v-model="isOn" />
*
* data() {
* return {
* isOn: false
* }
* }
*
*/
<template>
<label class="toggle" :class="checked?'checked':'unchecked'">
<input class="toggle-checkbox" type="checkbox" :checked="checked" @change="$emit('change', $event.target.checked)"/>
<div class="toggle-switch" :class="checked?(trueFalseColors[1]||'bg-primary'):(trueFalseColors[0]||'bg-gray-light')"></div>
<span v-show="trueFalseLabels[0]||trueFalseLabels[1]" class="toggle-label">{{checked?(trueFalseLabels[1]):(trueFalseLabels[0])}}</span>
</label>
</template>
<script>
export default {
model: {
prop: 'checked',
event: 'change'
},
props: {
"checked": { default: false },
"trueFalseLabels": { type:Array, default: () => ['',''] },
"trueFalseColors": { type:Array, default: () => ['bg-gray-light','bg-primary'] }
},
}
</script>
<style lang="postcss" scoped>
.toggle {
cursor: pointer;
display: inline-block;
}
.toggle-switch {
display: inline-block;
border-radius: 16px;
width: 45px;
height: 25px;
position: relative;
vertical-align: middle;
transition: background 0.25s;
}
.toggle-checkbox {
position: absolute;
visibility: hidden;
}
.toggle-label {
margin-left: 5px;
position: relative;
top: 2px;
}
.toggle.checked .toggle-switch {
/* @apply bg-primary; */
}
.toggle.checked .toggle-switch:before {
left: 22px;
}
.toggle-switch:before {
content: "";
display: block;
background: linear-gradient(to bottom, #fff 0%,#eee 100%);
border-radius: 50%;
box-shadow: 0 0 0 1px rgba(0,0,0,0.25);
width: 21px;
height: 21px;
position: absolute;
top: 2px;
left: 2px;
transition: left 0.25s;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment