[TOC]

将按钮中间变成圆形

<template>
    <button><span></span></button>
</template>

<style lang="scss" scoped>
  $h: 22px;
  $h2: $h - 4px;
  button {
      height: $h;
      width: $h*2;
      border: none;
      background: blue;
      border-radius: $h/2;
      position: relative;
  }
  span {
      position: absolute;
      top: 2px;
      left: 2px;
      height: $h2;
      width: $h2;
      background: white;
      border-radius: $h2/2;
  }
</style>

image.png

hover时向右移动

  button:hover > span {
      left: calc(100% - #{$h2} - 2px)
  }

image.png

点击时切换

<template>
    <button @click="toggle" :class="{checked}"><span></span></button>
</template>

<script lang="ts">
import { ref } from '@vue/reactivity'
export default {
  setup(){
     const checked = ref(false)
     const toggle = () => {
         checked.value = !checked.value
     }
     return {
         checked, toggle
     }
  }
}
</script>
  button.checked {
      background: blue;

      & > span {
          left: calc(100% - #{$h2} - 2px)
      }
  }

添加过渡

  span { 
    transition: left 250ms;
  }

  button:focus {
      outline: none;
  }

让组件接受props和监听状态变化

switchdemo中传入props,并监听input,$event为子组件事件抛出的值

<template>
    <div>
      <Switch :value="bool" @input="bool=$event"/>
    </div>
</template>

<script lang="ts">
import Switch from '../lib/Switch.vue'
import {ref} from 'vue'
export default {
    setup(){
        const bool = ref(true)
        return {
            bool
        }
    },
    components: {Switch}
}
</script>

switch组件

  • 由props接受外部数据
  • context.emit抛出事件 ```vue