vue实现带文字switch切换简化版

switch代码片段仅作为个人笔记

<template>
    <div class="toggle-button-wrapper">
        <input type="checkbox" id="toggle-button" name="switch" :checked="checked" v-on="listeners" @change="onChange">
        <label for="toggle-button" class="button-label">
            <span class="circle">{{ checked ? onText : offText }}</span>
        </label>
    </div>
</template>

<script>
    export default {
        name: "Switch",
        inheritAttrs:false,
        props: {
            onText:  {
                type: String,
                default: '开启'
            },
            offText: {
                type: String,
                default: '关闭'
            },
            propsChecked: {
              type: Boolean,
              default: false
            }
        },
        data() {
          return {
            checked: true
          }
        },
        computed: {
            listeners(){
                let result = Object.assign({}, this.$listeners);
                return result
            }
        },
        methods: {
          onChange(e) {
            this.checked = e.target.checked;
            this.$emit('change',e.target.checked);
          }
        },
        created() {
          this.checked = this.propsChecked;
        }
    }
</script>

<style>
#toggle-button {
  display: none;
}
.button-label {
  position: relative;
  display: inline-block;
  width: 180px;
  height: 60px;
  background: #FFFFFF;
  border: 0.9975px solid #E06565;
  border-radius: 31.9999px;
  box-sizing: border-box;
}
.circle {
  position: absolute;
  top: 0;
  width: 120px;
  height: 58.9999px;
  border-radius: 31.9999px;
  line-height: 60px;
  text-align: center;
  color: #fff;
  transition: all 0.3s ease;
}
.button-label .circle {
  left: -1px;
  right: auto;
  background: #FA607F;
  box-shadow: 0 5px 15px rgba(250, 96, 127, 0.4);
}
#toggle-button:checked + label.button-label {
  border: 0.9975px solid #5E6FFA;
  font-size: 24px;
}
#toggle-button:checked + label.button-label .circle {
  left: 60px;
  right: -1px;
  background: #5D75F7;
  box-shadow: 0 5px 15px 0 rgba(94, 111, 250, 0.4);
}


</style>

猜你喜欢

转载自www.cnblogs.com/Lewiskycc/p/11687060.html
今日推荐