我们在开发当中有一种场景,需要我们有一个开关,这个开关代表2种状态,这个时候我们就可以使用这样一个自定义的switch开关来表示2种不同的状态或者模式 ,下面直接上代码。

switch开关切换

我们把这个开关封装为一个组件,方便我们可以四处使用!然后利用父子传值,将我们改变的状态值传递给父组件,这样父组件就可以根据我们传出来的不同状态值做相应的逻辑处理。

<!-- components/SwitchComponent.vue -->
<template>
	<view class="switch-container" :style="[isActive ?  { backgroundColor: '#FFDDAA' }: { backgroundColor: '#fff' }]"
		:class="{ active: isActive }" @click="toggleState">
		<view class="switch-button blue">选 择</view>
		<view class="switch-button orange">填 写</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isActive: false
			};
		},
		methods: {
			toggleState() {
				this.isActive = !this.isActive;
				this.$emit('changeFromMode', this.isActive)
			}
		}
	};
</script>

<style lang="scss" scoped>
	/* 将上述CSS样式放入这里,但注意使用scoped来避免样式冲突 */
	.switch-container {
		width: 200rpx;
		height: 60rpx;
		border-radius: 60rpx;
		position: relative;
		overflow: hidden;
		cursor: pointer;
		user-select: none;
		background-color: #fff;
		box-shadow: 2rpx 4rpx 10rpx #c4c4c4;
		transition: all .1s ease;
	}

	.switch-button {
		width: 120rpx;
		height: 60rpx;
		border-radius: 30rpx;
		text-align: center;
		line-height: 60rpx;
		font-size: 28rpx;
		transition: transform 0.3s ease;
	}

	.blue {
		position: absolute;
		top: 0;
		left: 0;
		background-color: #6991f2;
		color: white;
		box-shadow: 2rpx 4rpx 10rpx #6991f2;
	}

	.orange {
		position: absolute;
		top: 0;
		left: 0rpx;
		background-color: #FF8800;
		box-shadow: 2rpx 4rpx 10rpx #FF8800;
		color: white;
		transform: translateX(200rpx);
	}

	.switch-container.active .blue {
		transform: translateX(-400rpx);
	}

	.switch-container.active .orange {
		transform: translateX(80rpx);
	}
</style>

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐