useBoolean 钩子函数文档
一、功能概述
useBoolean 是基于 Vue 3 的响应式状态管理钩子,用于简化布尔值状态的管理。它通过 ref 创建响应式变量,并提供一组便捷方法来操作布尔值,适用于控制模态框显示/隐藏、开关状态、加载状态等场景。
二、核心特性
响应式状态
使用ref实现响应式布尔值bool,状态变化时自动触发视图更新。多功能操作方法
setBool(value: boolean):直接设置布尔值setTrue():快速将状态设为truesetFalse():快速将状态设为falsetoggle():切换状态(取反)
灵活初始状态
支持传入初始值initValue(默认值为false),可根据业务需求自定义初始状态。
三、API 接口说明
函数参数
| 参数名 | 类型 | 默认值 | 说明 |
|---|---|---|---|
initValue | boolean | false | 布尔值的初始状态 |
返回值
| 名称 | 类型 | 说明 |
|---|---|---|
bool | Ref<boolean> | 响应式布尔值引用 |
setBool | (value: boolean) => void | 直接设置布尔值 |
setTrue | () => void | 将状态设为 true |
setFalse | () => void | 将状态设为 false |
toggle | () => void | 切换状态(取反) |
四、典型使用场景
场景 1:模态框显示/隐藏控制
vue
<template>
<div>
<button @click="showModal">打开模态框</button>
<Transition name="fade">
<div v-show="modalVisible" class="modal" @click="hideModal">
<div class="modal-content">
<p>模态框内容</p>
<button @click="hideModal">关闭</button>
</div>
</div>
</Transition>
</div>
</template>
<script setup>
import { useBoolean } from '@eco-library/hooks';
const { bool: modalVisible, setTrue: showModal, setFalse: hideModal } = useBoolean();
</script>
<style scoped>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
opacity: 0;
}
.fade-enter-active {
opacity: 1;
}
.fade-leave-active {
opacity: 0;
}
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
}
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 20px;
border-radius: 8px;
}
</style>场景 2:开关按钮状态切换
vue
<template>
<button @click="toggleStatus" class="switch-btn">
{{ status ? '开启' : '关闭' }}
</button>
</template>
<script setup>
import { useBoolean } from '@eco-library/hooks';
const { bool: status, toggle: toggleStatus } = useBoolean(true); // 初始状态为开启
</script>
<style scoped>
.switch-btn {
padding: 8px 16px;
border: none;
border-radius: 24px;
background-color: {{ status ? '#4CAF50' : '#f44336' }};
color: white;
cursor: pointer;
}
</style>场景 3:表单验证状态管理
vue
<template>
<form @submit.prevent="handleSubmit">
<input type="text" v-model="inputValue" placeholder="请输入内容" />
<button :disabled="!formValid">提交</button>
<p v-show="errorVisible">内容不能为空!</p>
</form>
</template>
<script setup>
import { useBoolean } from '@eco-library/hooks';
const inputValue = ref('');
const { bool: formValid, setTrue: validateForm, setFalse: resetForm } = useBoolean(false);
const { bool: errorVisible, setTrue: showError, setFalse: hideError } = useBoolean();
const handleSubmit = () => {
if (inputValue.value.trim()) {
validateForm();
hideError();
} else {
resetForm();
showError();
}
};
</script>五、注意事项
响应式访问规则
通过ref创建的bool需通过.value访问其值(如bool.value = true),模板中可直接使用bool绑定(如v-show="bool")。方法传递最佳实践
向子组件传递方法时,建议使用箭头函数包裹以避免上下文丢失:vue<ChildComponent @toggle="() => toggle()" />类型安全保障
setBool方法严格校验参数类型,仅接受布尔值,避免非预期状态变更。
六、扩展与组合
扩展:异步操作状态管理
typescript
// useAsyncBoolean.ts
import { useBoolean } from '@eco-library/hooks';
export function useAsyncBoolean(initValue = false) {
const { bool, setTrue, setFalse, toggle } = useBoolean(initValue);
const runAsync = async (asyncFn: () => Promise<void>) => {
setTrue(); // 开始加载
try {
await asyncFn(); // 执行异步操作
} catch (error) {
console.error('异步操作失败:', error);
} finally {
setFalse(); // 结束加载
}
};
return { ...{ bool, toggle }, runAsync };
}组合:防抖切换状态
typescript
// useDebouncedToggle.ts
import { useBoolean } from '@eco-library/hooks';
import { useDebounceFn } from '@vueuse/core';
export function useDebouncedToggle(initValue = false, debounceTime = 300) {
const { toggle: originalToggle, ...rest } = useBoolean(initValue);
const debouncedToggle = useDebounceFn(originalToggle, debounceTime);
return { ...rest, toggle: debouncedToggle };
}七、依赖说明
- 运行环境:Vue 3.x(需安装
vue@^3.0.0) - 打包工具:支持 Vite、Webpack 等主流构建工具
- 类型支持:内置 TypeScript 类型定义,无需额外声明
