完整的代码, 可以复制引用
功能开关的组件, 左右开关
<template>
<div>
<div>
<!-- 切换面板,通过点击事件来改变flag的值 -->
<div class="switch-panel" @click="toggleFlag" :class="{'switch-left': flag,'switch-right': !flag}">
<span class="switch-ico"></span>
{{ getFlag }}
</div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
// flag表示开关状态,true表示开,false表示关
flag: true,
}
},
methods: {
// 点击切换开关状态的方法
toggleFlag () {
this.flag = !this.flag;
}
},
computed: {
// 用于获取flag的值
getFlag () {
return this.flag;
}
}
}
</script>
<style>
/* 开关面板的基础样式 */
.switch-panel {
position: relative;
transition: 1s;
width: 50px;
height: 20px;
border-radius: 20px;
background: #13CE66;
cursor: pointer;
}
/* 开关图标的样式 */
.switch-ico {
transition: .5s;
float: left;
margin-top: 1px;
width: 18px;
height: 18px;
background: #fff;
border-radius: 50%;
}
/* 当开关在左侧时的样式 */
.switch-left {
background: red;
}
/* 当开关在右侧时的样式 */
.switch-right {
background: #13CE66;
}
/* 开关图标在左侧和右侧时的位移 */
.switch-left .switch-ico {
transform: translateX(0);
}
.switch-right .switch-ico {
transform: translateX(30px);
}
</style>