需要实现的效果
标题代码实现
<div class="custom-switch" :class="{ 'active': value }" @click="toggle">
<span class="custom_left" v-if="value">关灯</span>
<div class="switch-btn"></div>
<span class="custom_right" v-if="values">开灯</span>
</div>
</template>
<script>
export default {
props: {
value: {
type: Boolean,
default: false,
},
label: {
type: String,
required: true,
},
},
data() {
return {
values: true
}
},
methods: {
toggle() {
this.values = !this.values
this.$emit('input', !this.value);
},
},
};
</script>
<style scoped>
.custom-switch {
width: 130rpx;
height: 64rpx;
border-radius: 50rpx;
background-color: #B2B2B2;
cursor: pointer;
position: relative;
transition: background-color .3s;
}
.custom-switch.active {
background-color: #07c160;
}
.custom-switch span {
color: #666;
font-size: 14px;
display: inline-block;
margin-top: 15rpx;
font-size: 24rpx;
font-family: PingFang SC-Bold, PingFang SC;
font-weight: bold;
}
.custom_left {
float: left;
color: #008744;
margin-left: 16rpx;
}
.custom_right {
float: right;
color: #8D8D8D;
opacity: 100%;
margin-right: 16rpx;
}
.switch-btn {
width: 52rpx;
height: 52rpx;
position: absolute;
left: 6rpx;
top: 6rpx;
border-radius: 50%;
background-color: #fff;
box-shadow: 0 1px 2px rgba(0, 0, 0, .2);
transition: transform .3s, background-color .3s;
}
.custom-switch.active .switch-btn {
transform: translateX(66rpx);
background-color: #fff;
}
</style>
在上面的代码中,我们通过 props 属性定义了组件需要接收的参数:
value: 表示开关的状态,必须为 Boolean 类型,默认值为 false。
在组件内部,我们使用了一个 div 元素作为开关的容器,并且监听了容器的 click 事件。当容器被点击时,调用 toggle 方法改变开关的状态,并通过 $emit 方法向父组件发送 input 事件。
在样式方面,我们定义了开关容器的样式、开关按钮的样式以及选中时的样式,从而实现了一个简单的自定义 Switch 组件。
使用自定义 Switch 组件的方式与使用 uView 中的 Switch 开关选择器是相似的。在父组件中引入 switchs 组件,并将组件的 value 绑定到父组件的数据中,即可实现开关的功能。
在父元素中使用:
<template>
<div>
<switchs v-model="state" ></switchs>
</div>
</template>
<script>
import CustomSwitch from '@/components/CustomSwitch.vue';
export default {
components: {
CustomSwitch,
},
data() {
return {
state: false,
};
},
};
</script>
在上面的代码中,我们通过 import 关键字引入了自定义的 Switch 组件,并在 components 属性中注册。然后,在模板中使用 switchs 标签引入组件,并将 v-model 指令绑定到 state数据中,表示开关的状态
这样就可以在页面中使用自定义 Switch 组件,并且实现了加入文字的效果。