Skip to content
On this page

useToggle

功能说明

用于切换布尔值状态的简单 Hook。

适用场景

  • ✅ 弹窗显示/隐藏
  • ✅ 开关按钮

快速开始

vue
<script setup>
import { useToggle } from '@/hooks/vue/useToggle';
const [value, toggle] = useToggle(false);
</script>

<template>
  <button @click="toggle">当前状态: {{ value }}</button>
</template>
1
2
3
4
5
6
7
8

API 文档

参数

参数类型默认值必填说明
initialValuebooleanfalse初始状态

返回值

属性类型说明
valueRef<boolean>当前值
toggle() => void切换函数

完整代码

点击查看
typescript
import { ref } from 'vue';

export function useToggle(initialValue = false) {
  const state = ref(initialValue);
  const toggle = () => {
    state.value = !state.value;
  };
  return [state, toggle] as const;
}
1
2
3
4
5
6
7
8
9