Vue3开关(Switch)

简介: 这是一个可高度定制的开关组件,支持设置选中与未选中时的内容、值、大小、加载状态、禁用状态及点击波纹颜色等属性。组件提供了多种尺寸选择,并允许自定义图标与样式,适用于多种场景下的开关功能实现。[在线预览](https://themusecatcher.github.io/vue-amazing-ui/guide/components/switch.html)展示了其丰富的配置选项和实际效果。

可自定义设置以下属性:

  • 选中时的内容(checked),类型:string | slot,默认 undefined

  • 选中时的值(checkedValue),类型:boolean | string | number,默认 true

  • 未选中时的内容(unchecked),类型:string | slot,默认 undefined

  • 未选中时的值(uncheckedValue),类型:boolean | string | number,默认 false

  • 是否加载中(loading),类型:boolean,默认 false

  • 是否禁用(disabled),类型:boolean,默认 false

  • 开关大小(size),类型:'small' | 'middle' | 'large',默认 'middle'

  • 点击时的波纹颜色(rippleColor),当自定义选中颜色时需要设置,类型:string,默认 '#1677ff'

  • 圆点样式(circleStyle),类型:CSSProperties,默认 {}

  • 指定当前是否选中(v-model:modelValue),类型:boolean | string | number,默认 false

效果如下图:在线预览

①创建开关组件Switch.vue:

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import type { CSSProperties } from 'vue'
interface Props {
  checked?: string // 选中时的内容 string | slot
  checkedValue?: boolean | string | number // 选中时的值
  unchecked?: string // 未选中时的内容 string | slot
  uncheckedValue?: boolean | string | number // 未选中时的值
  loading?: boolean // 是否加载中
  disabled?: boolean // 是否禁用
  size?: 'small' | 'middle' | 'large' // 开关大小
  rippleColor?: string // 点击时的波纹颜色,当自定义选中颜色时需要设置
  circleStyle?: CSSProperties // 圆点样式
  modelValue?: boolean | string | number // (v-model) 指定当前是否选中
}
const props = withDefaults(defineProps<Props>(), {
  checked: undefined,
  checkedValue: true,
  unchecked: undefined,
  uncheckedValue: false,
  loading: false,
  disabled: false,
  size: 'middle',
  rippleColor: '#1677ff',
  circleStyle: () => ({}),
  modelValue: false
})
const wave = ref(false)
const emit = defineEmits(['update:modelValue', 'change'])
function onSwitch() {
  if (props.modelValue === props.checkedValue) {
    emit('update:modelValue', props.uncheckedValue)
    emit('change', props.uncheckedValue)
  } else {
    emit('update:modelValue', props.checkedValue)
    emit('change', props.checkedValue)
  }
  if (wave.value) {
    wave.value = false
    nextTick(() => {
      wave.value = true
    })
  } else {
    wave.value = true
  }
}
function onWaveEnd() {
  wave.value = false
}
</script>
<template>
  <div
    class="m-switch"
    :class="{
      'switch-loading': loading,
      'switch-small': size === 'small',
      'switch-large': size === 'large',
      'switch-checked': modelValue === checkedValue,
      'switch-disabled': disabled
    }"
    :style="`--ripple-color: ${rippleColor};`"
    @click="disabled || loading ? () => false : onSwitch()"
  >
    <div class="switch-inner">
      <span class="inner-checked">
        <slot name="checked">{
  
  { checked }}</slot>
      </span>
      <span class="inner-unchecked">
        <slot name="unchecked">{
  
  { unchecked }}</slot>
      </span>
    </div>
    <div class="switch-circle" :style="circleStyle">
      <svg v-if="loading" class="circular" viewBox="0 0 50 50">
        <circle class="path" cx="25" cy="25" r="20" fill="none"></circle>
      </svg>
      <slot name="node" :checked="modelValue"></slot>
    </div>
    <div v-if="!disabled" class="switch-wave" :class="{ 'wave-active': wave }" @animationend="onWaveEnd"></div>
  </div>
</template>
<style lang="less" scoped>
.m-switch {
  position: relative;
  display: inline-flex;
  align-items: center;
  vertical-align: middle;
  min-width: 44px;
  height: 22px;
  color: rgba(0, 0, 0, 0.88);
  font-size: 14px;
  line-height: 22px;
  background: rgba(0, 0, 0, 0.25);
  border-radius: 100px;
  cursor: pointer;
  transition: all 0.2s;
  user-select: none;
  &:hover:not(.switch-disabled) {
    background: rgba(0, 0, 0, 0.45);
  }
  .switch-inner {
    display: block;
    overflow: hidden;
    border-radius: 100px;
    height: 100%;
    padding-left: 24px;
    padding-right: 9px;
    transition:
      padding-left 0.2s ease-in-out,
      padding-right 0.2s ease-in-out;
    .inner-checked {
      margin-left: calc(-100% + 22px - 48px);
      margin-right: calc(100% - 22px + 48px);
      display: block;
      text-align: center;
      color: #fff;
      font-size: 14px;
      transition:
        margin-left 0.2s ease-in-out,
        margin-right 0.2s ease-in-out;
      pointer-events: none;
    }
    .inner-unchecked {
      margin-top: -22px;
      margin-left: 0;
      margin-right: 0;
      display: block;
      text-align: center;
      color: #fff;
      font-size: 14px;
      transition:
        margin-left 0.2s ease-in-out,
        margin-right 0.2s ease-in-out;
      pointer-events: none;
    }
  }
  .switch-circle {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 2px;
    left: 2px;
    width: 18px;
    height: 18px;
    background: #fff;
    border-radius: 100%;
    transition: all 0.2s ease-in-out;
    .circular {
      position: absolute;
      inset: 0;
      margin: auto;
      width: 14px;
      height: 14px;
      animation: loading-rotate 2s linear infinite;
      -webkit-animation: loading-rotate 2s linear infinite;
      @keyframes loading-rotate {
        100% {
          transform: rotate(360deg);
        }
      }
      .path {
        stroke-dasharray: 90, 150;
        stroke-dashoffset: 0;
        stroke: @themeColor;
        stroke-width: 5;
        stroke-linecap: round;
        animation: loading-dash 1.5s ease-in-out infinite;
        -webkit-animation: loading-dash 1.5s ease-in-out infinite;
        @keyframes loading-dash {
          0% {
            stroke-dasharray: 1, 200;
            stroke-dashoffset: 0;
          }
          50% {
            stroke-dasharray: 90, 150;
            stroke-dashoffset: -40px;
          }
          100% {
            stroke-dasharray: 90, 150;
            stroke-dashoffset: -120px;
          }
        }
      }
    }
  }
}
.switch-loading {
  cursor: not-allowed;
  opacity: 0.65;
  .switch-inner,
  .switch-circle {
    box-shadow: none;
    cursor: not-allowed;
  }
}
.switch-small {
  min-width: 28px;
  height: 16px;
  line-height: 16px;
  .switch-inner {
    padding-left: 18px;
    padding-right: 6px;
    .inner-checked {
      font-size: 12px;
      margin-left: calc(-100% + 16px - 36px);
      margin-right: calc(100% - 16px + 36px);
    }
    .inner-unchecked {
      font-size: 12px;
      margin-top: -16px;
    }
  }
  .switch-circle {
    width: 12px;
    height: 12px;
    .circular {
      width: 10px;
      height: 10px;
      .path {
        stroke-width: 4;
      }
    }
  }
}
.switch-large {
  min-width: 60px;
  height: 28px;
  line-height: 28px;
  .switch-inner {
    padding-left: 30px;
    padding-right: 12px;
    .inner-checked {
      font-size: 18px;
      margin-left: calc(-100% + 28px - 60px);
      margin-right: calc(100% - 28px + 60px);
    }
    .inner-unchecked {
      font-size: 18px;
      margin-top: -28px;
    }
  }
  .switch-circle {
    width: 24px;
    height: 24px;
    .circular {
      width: 20px;
      height: 20px;
      .path {
        stroke-width: 6;
      }
    }
  }
}
.switch-checked {
  background: @themeColor;
  &:hover:not(.switch-disabled) {
    background: #4096ff;
  }
  .switch-inner {
    padding-left: 9px;
    padding-right: 24px;
    .inner-checked {
      margin-left: 0;
      margin-right: 0;
    }
    .inner-unchecked {
      margin-left: calc(100% - 22px + 48px);
      margin-right: calc(-100% + 22px - 48px);
    }
  }
  .switch-circle {
    left: calc(100% - 20px);
  }
}
.switch-small.switch-checked {
  .switch-inner {
    padding-left: 6px;
    padding-right: 18px;
    .inner-unchecked {
      margin-left: calc(100% - 16px + 36px);
      margin-right: calc(-100% + 16px - 36px);
    }
  }
  .switch-circle {
    left: calc(100% - 14px);
  }
}
.switch-large.switch-checked {
  .switch-inner {
    padding-left: 12px;
    padding-right: 30px;
    .inner-unchecked {
      margin-left: calc(100% - 28px + 60px);
      margin-right: calc(-100% + 28px - 60px);
    }
  }
  .switch-circle {
    left: calc(100% - 26px);
  }
}
.switch-disabled {
  cursor: not-allowed;
  opacity: 0.65;
  .switch-circle {
    cursor: not-allowed;
  }
}
.switch-wave {
  position: absolute;
  pointer-events: none;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  animation-iteration-count: 1;
  animation-duration: 0.6s;
  animation-timing-function: cubic-bezier(0, 0, 0.2, 1), cubic-bezier(0, 0, 0.2, 1);
  border-radius: inherit;
}
.wave-active {
  z-index: 1;
  animation-name: wave-spread, wave-opacity;
  @keyframes wave-spread {
    from {
      box-shadow: 0 0 0.5px 0 var(--ripple-color);
    }
    to {
      box-shadow: 0 0 0.5px 5px var(--ripple-color);
    }
  }
  @keyframes wave-opacity {
    from {
      opacity: 0.6;
    }
    to {
      opacity: 0;
    }
  }
}
</style>

②在要使用的页面引入:

<script setup lang="ts">
import Switch from './Switch.vue'
import { ref, watchEffect } from 'vue'

const checked = ref(true)
const customValue1 = ref('no')
const customValue2 = ref(2)
function onChange(checked: boolean) {
  console.log('checked:', checked)
}
watchEffect(() => {
  console.log('checked:', checked.value)
})
</script>
<template>
  <div>
    <h1>{
  
  { $route.name }} {
  
  { $route.meta.title }}</h1>
    <h2 class="mt30 mb10">基本使用</h2>
    <Switch v-model="checked" @change="onChange" />
    <h2 class="mt30 mb10">禁用开关</h2>
    <Switch v-model="checked" disabled />
    <h2 class="mt30 mb10">三种大小</h2>
    <Space>
      <Switch v-model="checked" size="small" />
      <Switch v-model="checked" />
      <Switch v-model="checked" size="large" />
    </Space>
    <h2 class="mt30 mb10">加载中</h2>
    <Space>
      <Switch v-model="checked" size="small" loading />
      <Switch v-model="checked" loading />
      <Switch v-model="checked" size="large" loading />
    </Space>
    <h2 class="mt30 mb10">带 文字 / 数字 / 字母 的开关</h2>
    <Space>
      <Switch v-model="checked" checked="开" unchecked="关" />
      <Switch v-model="checked" checked="1" unchecked="0" />
      <Switch v-model="checked" checked="yes" unchecked="no" />
    </Space>
    <h2 class="mt30 mb10">自定义图标和样式</h2>
    <Switch
      class="u-theme-switch"
      v-model="checked"
      ripple-color="#faad14"
      :circle-style="{ background: checked ? '#001529' : '#fff' }"
    >
      <template #node="{ checked }">
        <svg
          v-if="checked"
          xmlns="http://www.w3.org/2000/svg"
          aria-hidden="true"
          focusable="false"
          viewBox="0 0 24 24"
          class="u-dark-svg"
        >
          <path
            d="M12.1,22c-0.3,0-0.6,0-0.9,0c-5.5-0.5-9.5-5.4-9-10.9c0.4-4.8,4.2-8.6,9-9c0.4,0,0.8,0.2,1,0.5c0.2,0.3,0.2,0.8-0.1,1.1c-2,2.7-1.4,6.4,1.3,8.4c2.1,1.6,5,1.6,7.1,0c0.3-0.2,0.7-0.3,1.1-0.1c0.3,0.2,0.5,0.6,0.5,1c-0.2,2.7-1.5,5.1-3.6,6.8C16.6,21.2,14.4,22,12.1,22zM9.3,4.4c-2.9,1-5,3.6-5.2,6.8c-0.4,4.4,2.8,8.3,7.2,8.7c2.1,0.2,4.2-0.4,5.8-1.8c1.1-0.9,1.9-2.1,2.4-3.4c-2.5,0.9-5.3,0.5-7.5-1.1C9.2,11.4,8.1,7.7,9.3,4.4z"
          ></path>
        </svg>
        <svg
          v-else
          xmlns="http://www.w3.org/2000/svg"
          aria-hidden="true"
          focusable="false"
          viewBox="0 0 24 24"
          class="u-light-svg"
        >
          <path
            d="M12,18c-3.3,0-6-2.7-6-6s2.7-6,6-6s6,2.7,6,6S15.3,18,12,18zM12,8c-2.2,0-4,1.8-4,4c0,2.2,1.8,4,4,4c2.2,0,4-1.8,4-4C16,9.8,14.2,8,12,8z"
          ></path>
          <path d="M12,4c-0.6,0-1-0.4-1-1V1c0-0.6,0.4-1,1-1s1,0.4,1,1v2C13,3.6,12.6,4,12,4z"></path>
          <path d="M12,24c-0.6,0-1-0.4-1-1v-2c0-0.6,0.4-1,1-1s1,0.4,1,1v2C13,23.6,12.6,24,12,24z"></path>
          <path
            d="M5.6,6.6c-0.3,0-0.5-0.1-0.7-0.3L3.5,4.9c-0.4-0.4-0.4-1,0-1.4s1-0.4,1.4,0l1.4,1.4c0.4,0.4,0.4,1,0,1.4C6.2,6.5,5.9,6.6,5.6,6.6z"
          ></path>
          <path
            d="M19.8,20.8c-0.3,0-0.5-0.1-0.7-0.3l-1.4-1.4c-0.4-0.4-0.4-1,0-1.4s1-0.4,1.4,0l1.4,1.4c0.4,0.4,0.4,1,0,1.4C20.3,20.7,20,20.8,19.8,20.8z"
          ></path>
          <path d="M3,13H1c-0.6,0-1-0.4-1-1s0.4-1,1-1h2c0.6,0,1,0.4,1,1S3.6,13,3,13z"></path>
          <path d="M23,13h-2c-0.6,0-1-0.4-1-1s0.4-1,1-1h2c0.6,0,1,0.4,1,1S23.6,13,23,13z"></path>
          <path
            d="M4.2,20.8c-0.3,0-0.5-0.1-0.7-0.3c-0.4-0.4-0.4-1,0-1.4l1.4-1.4c0.4-0.4,1-0.4,1.4,0s0.4,1,0,1.4l-1.4,1.4C4.7,20.7,4.5,20.8,4.2,20.8z"
          ></path>
          <path
            d="M18.4,6.6c-0.3,0-0.5-0.1-0.7-0.3c-0.4-0.4-0.4-1,0-1.4l1.4-1.4c0.4-0.4,1-0.4,1.4,0s0.4,1,0,1.4l-1.4,1.4C18.9,6.5,18.6,6.6,18.4,6.6z"
          ></path>
        </svg>
      </template>
    </Switch>
    <h2 class="mt30 mb10">自定义选中的值</h2>
    <Space gap="large">
      <Space vertical align="center">
        <Switch v-model="customValue1" checked-value="on" unchecked-value="off">
          <template #checked>on</template>
          <template #unchecked>off</template>
        </Switch>
        Current Value: {
  
  { customValue1 }}
      </Space>
      <Space vertical align="center">
        <Switch v-model="customValue2" :checked-value="1" :unchecked-value="2">
          <template #checked>yes</template>
          <template #unchecked>no</template>
        </Switch>
        Current Value: {
  
  { customValue2 }}
      </Space>
    </Space>
  </div>
</template>
<style lang="less" scoped>
.u-theme-switch.switch-checked {
  background: #faad14;
  &:hover:not(.disabled) {
    background: #e8b339;
  }
}
.u-dark-svg {
  width: 12px;
  height: 12px;
  fill: #fff;
}
.u-light-svg {
  width: 12px;
  height: 12px;
  fill: rgba(60, 60, 67, 0.75);
}
</style>
相关文章
|
12天前
|
开发工具 iOS开发 MacOS
基于Vite7.1+Vue3+Pinia3+ArcoDesign网页版webos后台模板
最新版研发vite7+vue3.5+pinia3+arco-design仿macos/windows风格网页版OS系统Vite-Vue3-WebOS。
139 11
|
5月前
|
缓存 JavaScript PHP
斩获开发者口碑!SnowAdmin:基于 Vue3 的高颜值后台管理系统,3 步极速上手!
SnowAdmin 是一款基于 Vue3/TypeScript/Arco Design 的开源后台管理框架,以“清新优雅、开箱即用”为核心设计理念。提供角色权限精细化管理、多主题与暗黑模式切换、动态路由与页面缓存等功能,支持代码规范自动化校验及丰富组件库。通过模块化设计与前沿技术栈(Vite5/Pinia),显著提升开发效率,适合团队协作与长期维护。项目地址:[GitHub](https://github.com/WANG-Fan0912/SnowAdmin)。
750 5
|
2月前
|
缓存 前端开发 大数据
虚拟列表在Vue3中的具体应用场景有哪些?
虚拟列表在 Vue3 中通过仅渲染可视区域内容,显著提升大数据列表性能,适用于 ERP 表格、聊天界面、社交媒体、阅读器、日历及树形结构等场景,结合 `vue-virtual-scroller` 等工具可实现高效滚动与交互体验。
272 1
|
2月前
|
缓存 JavaScript UED
除了循环引用,Vue3还有哪些常见的性能优化技巧?
除了循环引用,Vue3还有哪些常见的性能优化技巧?
148 0
|
3月前
|
JavaScript
vue3循环引用自已实现
当渲染大量数据列表时,使用虚拟列表只渲染可视区域的内容,显著减少 DOM 节点数量。
99 0
|
5月前
|
JavaScript API 容器
Vue 3 中的 nextTick 使用详解与实战案例
Vue 3 中的 nextTick 使用详解与实战案例 在 Vue 3 的日常开发中,我们经常需要在数据变化后等待 DOM 更新完成再执行某些操作。此时,nextTick 就成了一个不可或缺的工具。本文将介绍 nextTick 的基本用法,并通过三个实战案例,展示它在表单验证、弹窗动画、自动聚焦等场景中的实际应用。
420 17
|
6月前
|
JavaScript 前端开发 算法
Vue 3 和 Vue 2 的区别及优点
Vue 3 和 Vue 2 的区别及优点
|
6月前
|
存储 JavaScript 前端开发
基于 ant-design-vue 和 Vue 3 封装的功能强大的表格组件
VTable 是一个基于 ant-design-vue 和 Vue 3 的多功能表格组件,支持列自定义、排序、本地化存储、行选择等功能。它继承了 Ant-Design-Vue Table 的所有特性并加以扩展,提供开箱即用的高性能体验。示例包括基础表格、可选择表格和自定义列渲染等。
417 6
|
5月前
|
JavaScript 前端开发 API
Vue 2 与 Vue 3 的区别:深度对比与迁移指南
Vue.js 是一个用于构建用户界面的渐进式 JavaScript 框架,在过去的几年里,Vue 2 一直是前端开发中的重要工具。而 Vue 3 作为其升级版本,带来了许多显著的改进和新特性。在本文中,我们将深入比较 Vue 2 和 Vue 3 的主要区别,帮助开发者更好地理解这两个版本之间的变化,并提供迁移建议。 1. Vue 3 的新特性概述 Vue 3 引入了许多新特性,使得开发体验更加流畅、灵活。以下是 Vue 3 的一些关键改进: 1.1 Composition API Composition API 是 Vue 3 的核心新特性之一。它改变了 Vue 组件的代码结构,使得逻辑组
1509 0
|
7月前
|
JavaScript 前端开发 UED
vue2和vue3的响应式原理有何不同?
大家好,我是V哥。本文详细对比了Vue 2与Vue 3的响应式原理:Vue 2基于`Object.defineProperty()`,适合小型项目但存在性能瓶颈;Vue 3采用`Proxy`,大幅优化初始化、更新性能及内存占用,更高效稳定。此外,我建议前端开发者关注鸿蒙趋势,2025年将是国产化替代关键期,推荐《鸿蒙 HarmonyOS 开发之路》卷1助你入行。老项目用Vue 2?不妨升级到Vue 3,提升用户体验!关注V哥爱编程,全栈开发轻松上手。
448 2