uni-app实现自定义switch组件

前言

项目需求需要用到switc带文字功能,翻阅了uniapp的官方文档发现switch不能加文字,于是自己打算写一个。

注意

采用的是vue2+ts写法

效果

关闭状态
开启状态

组件代码

<template>
  <view class="container">
    <!-- @click="switchClick(isChecked)" -->
    <label :class="isChecked ? 'switch-checked' : 'switch-nochecked'">
      <view class="open">开启</view>
      <view class="close">关闭</view>
    </label>
  </view>
</template>

<script lang="ts">
import Vue from "vue";
import { Component, Prop } from "vue-property-decorator";

@Component
export default class SwitchCustom extends Vue {
  @Prop({ required: false, default: false }) isChecked!: boolean;
}
</script>

<style lang="scss" scoped>
.container {
  width: 120rpx;

  label {
    position: relative;
    display: block;
    border-radius: 55rpx;
    height: 55rpx;
    width: 100%;
    &:before {
      content: " ";
      display: block;
      border-radius: 55rpx;
      height: 100%;
      background-color: #d5d5d5;
      transform: scale(1, 1);
      transition: all 0.3s ease;
    }
    &:after {
      content: " ";
      position: absolute;
      top: 9%;
      margin-left: 5%;
      width: 45rpx;
      height: 45rpx;
      border-radius: 45rpx;
      background-color: white;
      box-shadow: 2rpx rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;
    }
  }
  %font-style {
    top: 0;
    color: #ffffff;
    font-size: 20rpx;
    height: 100%;
    line-height: 55rpx;
    position: absolute;
    transition: all 1s ease;
  }
  .switch-checked {
    &:after {
      margin-left: calc(94% - 45rpx);
      left: unset;
    }
    &:before {
      background-color: #01a2ff;
    }
    .close {
      display: none;
    }
  }
  .switch-nochecked {
    .open {
      display: none;
    }
  }

  .open {
    left: 10rpx;
    @extend %font-style;
  }
  .close {
    right: 10rpx;
    @extend %font-style;
    color: #6b6b6b;
  }
}
</style>

使用

<switch-custom @click.native="formData.volunteer=formData.volunteer===1?0:1" :isChecked="formData.volunteer ? true : false"/>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值