做一个简单地switch开关

223 阅读1分钟

image.png

image.png

父组件:SwitchDome.vue

<template>
  <div>
    <Switch v-model:value = "y"/> //接收子组件的数据变化
  </div>
</template>
<script lang="ts">
import Switch from '../lib/Switch.vue'
import {ref} from  'vue'
export default {
  components:{Switch}, //引入Switch子组件
  setup(){
    const y = ref(false) //父组件传给子组件的默认值
    return {y}
  }
}

</script>

子组件:Switch.vue

<template>
  <button  class="gulu-switch" @click="toggle" :class="{'gulu-checked':value}"><span></span></button>//添加一个点击事件,添加一个动态名字 
</template>
<script>
export default {
  props:{
    value: Boolean//从父组件接收value,类型为Boolean
  },
  setup(props,context){
    const toggle = () => {
     context.emit('update:value', !props.value)//点击事件当用户点击的时候,将value变为相反值,并且updata:value是被父组件监听的事件,改变会将值传给父组件
    }
    return { toggle}
  }
}
</script>

<style lang="scss" >//css实现动画
$h: 44px;
$h2: $h - 4px;
.gulu-switch{
  height: $h;
  width: $h * 2;
  border: none;
  background: lightyellow;
  border-radius: $h/2;
  position: relative;
  box-shadow: 0 0 1px 1px #666;
}
span{                 
  position: absolute;
  left: 2px;
  top: 2px;
  height: $h2;
  width: $h2;
  border-radius: $h2/2;
  background:palevioletred;
  transition: all 250ms;//添加动画,从左向右添加250ms动画
}
button.gulu-checked {
  background: cadetblue;//当动态名字出现checked,做一些css变化
}
button.gulu-checked > span {
  background: greenyellow;
  left: calc(100% - #{$h2} - 2px)//将span从左移动到右边
}
.gulu-switch:focus{
  outline: none; //使用Tab的时候 默认周边的样式为none
}
.gulu-switch:hover{
  box-shadow: 0 0 6px 2px #666; //鼠标悬浮的时候出现阴影
}
.gulu-switch:active{
  > span {width: $h2 + 4px} //向活动的gulu-switch添加样式
}
button.gulu-checked:active{
  > span {width: $h2 + 4px; margin-left: -4px}
}
</style>