微信小程序(mpvue)實現switch組件(文字可選)


小程序開發過程中遇到的自定義組件 (開關帶文字)

附截圖


<template>
  <div class="toggle-button">
    <span class="weui-switch" :class="{'weui-switch-on' : checked}" :value="value" @click="toggle">
      <i class="weui-switch-text" :class="{'checked' : checked}">{{checked ? onText : offText}}</i>
    </span>
  </div>
</template>

<script>
export default {
    name: 'Switch',
    props: {
        onText: {
            type: String,
            default: ''
        },
        offText: {
            type: String,
            default: ''
        },
        propsChecked: {
            type: Boolean,
            default: false
        }
    },
    data () {
        return {
            checked: true
        };
    },
    methods: {
        toggle () {
            this.checked = !this.checked;
            this.$emit('change', this.checked);
        }
    },
    mounted () {
        this.checked = this.propsChecked;
    }
};
</script>

<style scoped lang="less">
.weui-switch {
  display: block;
  position: relative;
  width: 100rpx;
  height: 40rpx;
  border: 1rpx solid #DFDFDF;
  outline: 0;
  border-radius: 20rpx;
  box-sizing: border-box;
  background-color: #BBC2BE;
  transition: background-color 0.1s, border 0.1s;
  cursor: pointer;
}
.weui-switch:before {
  content: "";
  position: absolute;
  top: 2rpx;
  left: 0;
  width: 30rpx;
  height: 30rpx;
  border-radius: 15px;
  background-color: #FDFDFD;
  transition: transform 0.35s cubic-bezier(0.45, 1, 0.4, 1);
}
.weui-switch:after {
  content: "";
  position: absolute;
  top: 2rpx;
  left: 0;
  width: 30rpx;
  height: 30rpx;
  border-radius: 15rpx;
  background-color: #FFFFFF;
  transition: transform 0.35s cubic-bezier(0.4, 0.4, 0.25, 1.35);
}
.weui-switch-text {
  position: absolute;
  color: #ffffff;
  font-size: 24rpx;
  top: 50%;
  right: 12%;
  transform: translateY(-50%);
  &.checked {
    left: 10%;
  }
}
.weui-switch-on {
  border-color:#00B79D;
  background-color: #00B79D;
}
.weui-switch-on:before {
  border-color: #00B79D;
  background-color: #00B79D;
}
.weui-switch-on:after {
  transform: translateX(65rpx);
}
</style>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM