小程序开关组件

前提是vant组件库不太好改,干脆就手写了一个

javascript 复制代码
<template>
    <view class="switch-container" @click="toggleOrder">
        <view :class="['switch-text', 'left-text', { 'left-textChoose': isReverseOrder }]"
            >{{ leftText }}</view
        >
        <view class="switch-slider" :style="sliderStyle"></view>
        <view :class="['switch-text', 'right-text', { 'right-textChoose': !isReverseOrder }]"
            >{{ rightText }}</view
        >
    </view>
</template>

<script setup>
import { ref, computed } from 'vue';

const props = defineProps({
    leftText: {
        type: String,
        default: ''
    },
    rightText: {
        type: String,
        default: ''
    }
});
const isReverseOrder = ref(true);
const emit = defineEmits(['getValue']);
// 计算滑块的位置
const sliderStyle = computed(() => {
    // 滑块完全在左侧时偏移量为0%,完全在右侧时偏移量为100%
    return {
        transform: `translateX(${isReverseOrder.value ? '100%' : '0%'})`
    };
});

// 切换开关状态
function toggleOrder() {
    isReverseOrder.value = !isReverseOrder.value;
    console.log(isReverseOrder.value);
    emit('getValue', isReverseOrder.value);
}
</script>

<style scoped>
.switch-container {
    border: 2px solid #eeeeee;
    display: flex;
    align-items: center;
    width: 72px; 
    height: 28px; 
    background-color: #eeeeee; 
    border-radius: 20px; 
    overflow: hidden;
    position: relative; // 滑块绝对定位
}

.switch-text {
    flex: 1; //使文本元素占据剩余空间的一半
    display: flex;
    justify-content: center; 
    align-items: center;
    user-select: none; 
    position: relative; //为了可能的z-index调整
    z-index: 2; // 确保文本在滑块之上
}

.left-text {
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 10px;
    color: #25292f;
}
.left-textChoose {
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 10px;
    color: #25292f;
}

.right-text {
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 10px;
    color: #25292f;
}
.right-textChoose {
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 10px;
    color: #25292f;
}
.switch-slider {
    width: 50%; // 滑块宽度为容器宽度的一半
    height: 24px;
    background-color: #fff; 
    transition: transform 0.3s ease-in-out; // 过渡效果 
    border-radius: 20px; 
    position: absolute; // 绝对定位以覆盖整个容器 
    left: 0; //初始位置
    top: 0;
    bottom: 0;
    z-index: 1; // 确保滑块在文本之下
}
</style>

效果如图

相关推荐
難釋懷6 小时前
微信小程序全局配置
微信小程序·小程序
Enti7c6 小时前
微信小程序核心知识点速览
微信小程序·小程序
2501_9159184119 小时前
Fiddler中文版全面评测:功能亮点、使用场景与中文网资源整合指南
android·ios·小程序·https·uni-app·iphone·webview
说私域20 小时前
从品牌附庸到自我表达:定制开发开源AI智能名片S2B2C商城小程序赋能下的营销变革
人工智能·小程序
難釋懷20 小时前
第一个小程序
小程序
春哥的研究所20 小时前
可视化DIY小程序工具!开源拖拽式源码系统,自由搭建,完整的源代码包分享
小程序·开源·开源拖拽式源码系统·开源拖拽式源码·开源拖拽式系统
weixin_lynhgworld20 小时前
盲盒一番赏小程序技术实现方案:高并发与防作弊的平衡之道
小程序
今日热点21 小时前
小程序主体变更全攻略:流程、资料与异常处理方案
经验分享·微信·小程序·企业微信·微信公众平台·微信开放平台
鸭鸭梨吖1 天前
微信小程序---下拉框
微信小程序·小程序
mon_star°1 天前
搭建一款结合传统黄历功能的日历小程序
微信·微信小程序·小程序·微信公众平台