@oixg/switch
v1.0.1
Published
Switch component for Vue 3
Downloads
265
Readme
@oixg/switch
注意:仅支持 Vue 3.5+(使用了
useTemplateRef)
一个完全解耦的开关切换 composable。UI 完全由你控制,只提供交互逻辑和位置计算。
安装
npm install @oixg/switch用法
你只需要一个容器和一个滑块元素,useSwitch 帮你计算滑块位置并管理交互状态。
<script setup lang="ts">
import { useSwitch } from '@oixg/switch'
import { useTemplateRef } from 'vue'
const box = useTemplateRef('box')
const handle = useTemplateRef('handle')
const { active, handleStyle, toggle, ready } = useSwitch({
box, handle, duration: 300
})
</script>
<template>
<div
ref="box"
class="w-20 h-8 rounded-full flex items-center transition-colors duration-300"
:class="[active ? 'bg-blue-400' : 'bg-purple-200']"
@click="toggle"
>
<div
ref="handle"
class="h-12 aspect-square bg-blue-200 rounded-full"
:class="[ready ? 'transition-transform duration-300 ease-out' : 'transition-none']"
:style="handleStyle"
/>
</div>
</template>
duration只需在useSwitch参数中声明一次,模板中的 CSS 过渡时长由你自行保持同步。
API
useSwitch(options)
配置
| 参数 | 类型 | 说明 |
|------|------|------|
| box | Ref<HTMLElement \| null> | 开关容器的 template ref |
| handle | Ref<HTMLElement \| null> | 滑块元素的 template ref |
| duration | number | 过渡动画时长(毫秒),用于控制初次挂载时跳过动画的时机以及快速点击防抖 |
返回值
| 返回值 | 类型 | 说明 |
|--------|------|------|
| active | Ref<boolean> | 开关状态 |
| handleStyle | ComputedRef<{ transform: string }> | 滑块位移样式,绑定到滑块的 :style |
| toggle | () => void | 切换开关状态(动画期间禁用,防止快速点击) |
| setActive | (v: boolean) => void | 手动设置状态 |
| activate | () => void | 打开 |
| deactivate | () => void | 关闭 |
| ready | Ref<boolean> | 组件首次挂载 duration 毫秒后变为 true,用于跳过首次渲染的入场动画 |
| disabled | Ref<boolean> | 动画进行中时为 true,可借此添加禁用样式(如 opacity-50) |
工作原理
useSwitch 内部通过 ResizeObserver 监听容器和滑块的尺寸变化,结合 computed 实时计算滑块位移。不依赖任何外部 UI 库,由你决定开关的样式、配色、尺寸。
