@liuheo/vueuse
v0.0.16
Published
vue工具库
Maintainers
Readme
✨ 特性
- 🎯 基于 Vue 3 Composition API 设计
- 📦 开箱即用,提供丰富的工具函数
- 📝 完整的 TypeScript 类型支持
- 🔧 模块化设计,按需导入
- 🎨 适用于企业级后台管理系统开发
📦 安装
# npm
npm install @liuheo/vueuse
# or pnpm
pnpm add @liuheo/vueuse
# or yarn
yarn add @liuheo/vueuse依赖要求
本库需要以下 peer dependencies:
{
"vue": "^3.5.25",
"@vueuse/core": "^14.1.0",
"lodash-es": "^4.17.21"
}🚀 快速开始
// 按需导入所需函数
import { useSearch, useCopy, usePagination, useFetchList, useDragHelper } from "@liuheo/vueuse";📚 API 文档
数组工具 (Array)
useSearch<T>()
搜索数据工具函数,支持按指定字段或全字段搜索。
const { keywords, searchData } = useSearch<MyData>();
// 搜索指定字段
searchData(originalData, resultData, ["name", "email"]);
// 搜索所有字段
searchData(originalData, resultData);返回值:
| 属性 | 类型 | 说明 |
|------|------|------|
| keywords | Ref<string> | 搜索关键词 |
| searchData | Function | 执行搜索的函数 |
参数:
targetData: 原始数据数组resultData: 用于接收搜索结果的 refkeys?: 要搜索的字段键名数组(可选)
浏览器工具 (Browser)
useCopy(value, msgFunc?)
复制文本到剪贴板,支持对象自动转 JSON。
// 复制文本
useCopy("要复制的文本", (msg, type) => {
showMessage(msg, type);
});
// 复制对象(自动转为 JSON)
useCopy({ name: "张三" }, msgFunc);参数:
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| value | unknown | 是 | 要复制的值 |
| msgFunc | MsgFunc | 否 | 消息提示回调 |
组件工具 (Component)
useCompRef<T>(comp?, arr?)
获取组件实例的类型安全 ref。
// 单个组件实例
const compRef = useCompRef<MyComponent>();
// 组件实例数组
const compListRef = useCompRef<MyComponent>(undefined, true);参数:
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| comp | T | 否 | 组件类型 |
| arr | boolean | 否 | 是否返回数组,默认 false |
HTTP 请求工具 (HTTP)
useFetchMapHelper<T>(api, mapKey?, initialQuery?, callback?)
获取映射数据,构建键值映射表,适用于下拉选项等场景。
const [fetchData, dataMap, dataList, isLoading] = useFetchMapHelper<User>(
api.getUsers,
"id", // 映射键
{ status: 1 }, // 初始查询参数
(data) => console.log(data), // 回调
);
await fetchData({ extra: "param" });
// 使用映射表快速查找
const user = dataMap.value["123"];返回值:
| 属性 | 类型 | 说明 |
|------|------|------|
| fetchData | Function | 获取数据函数 |
| dataMap | ShallowRef<Record<string, T>> | 数据映射表 |
| dataList | ShallowRef<T[]> | 数据列表 |
| isLoading | ShallowRef<boolean> | 加载状态 |
useFetchOperation(api, data?, callback?, msgFunc?)
执行操作请求(如新增、删除、更新)。
await useFetchOperation(
api.deleteUser,
{ id: 1 },
{
success: (resp) => {
console.log("成功", resp);
refreshList();
},
fail: (resp) => console.log("失败", resp),
},
msgFunc,
);参数:
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| api | Function | 是 | 请求接口函数 |
| data | Recordable | 否 | 请求参数,默认 {} |
| callback | OperationCallback | 否 | 成功/失败回调 |
| msgFunc | MsgFunc | 否 | 消息提示回调 |
useFetchData<T>(api, ...args)
获取单条数据。
const { isLoading, data, isExist, fetchData } = useFetchData<User>(
api.getUserDetail,
{ id: 1 }, // 查询参数
(data, isExist) => console.log(data, isExist), // 回调
);
await fetchData();返回值:
| 属性 | 类型 | 说明 |
|------|------|------|
| isLoading | Ref<boolean> | 加载状态 |
| data | Ref<T | null> | 响应数据 |
| isExist | Ref<boolean> | 数据是否存在 |
| fetchData | Function | 获取数据函数 |
useFetchList<T, F>(api, pagination, queryParameter?, queryConfig?)
获取列表数据(支持分页和加载更多)。
const pagination = usePagination(10);
const { isLoading, dataList, filter, onList, handleLoad } = useFetchList<User>(
api.getUserList,
pagination,
{ status: 1 },
{
callback: {
success: (data) => console.log("数据加载成功", data),
watcher: (newVal) => console.log("参数变化", newVal),
},
},
);
// 刷新列表
await onList();
// 加载更多
await handleLoad();返回值:
| 属性 | 类型 | 说明 |
|------|------|------|
| isLoading | Ref<boolean> | 加载状态 |
| dataList | Ref<T[]> | 数据列表 |
| filter | Ref<F | null> | 过滤条件 |
| onList | Function | 获取数据(支持追加模式) |
| handleLoad | Function | 加载更多数据 |
特性:
- 自动监听
queryParameter变化并重新请求 - 支持追加模式加载数据
- 自动更新分页信息
布局工具 (Layout)
useDragHelper<T>(dataList, delay?)
拖拽排序工具,支持延迟交换防止误操作。
const dataList = ref([{ id: 1 }, { id: 2 }, { id: 3 }]);
const { onDragStart, onDragenter, dragover } = useDragHelper(dataList, 100);模板使用示例:
<div
v-for="(item, index) in dataList"
:key="item.id"
draggable="true"
@dragstart="onDragStart(index)"
@dragenter="onDragenter($event, index)"
@dragover="dragover($event)"
>
{{ item.name }}
</div>返回值:
| 属性 | 说明 |
|------|------|
| onDragStart(index) | 拖拽开始 |
| onDragenter(e, index) | 拖拽进入 |
| dragover(e) | 阻止默认事件 |
useJudgeDevice()
判断设备类型(移动端/桌面端),自动监听窗口变化。
const { isMobile, setDeviceInfo } = useJudgeDevice();
if (isMobile.value) {
console.log("移动端");
}返回值:
| 属性 | 类型 | 说明 |
|------|------|------|
| isMobile | Ref<boolean> | 是否为移动端 |
| setDeviceInfo | Function | 手动检测设备信息 |
useElementHeight(selectors, distance?)
获取元素可用高度,自动监听窗口变化。
const { height, getHeight } = useElementHeight("#content", 20);
console.log(height.value); // 可用高度参数:
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| selectors | string | 是 | 目标元素选择器 |
| distance | number | 否 | 额外距离,默认 0 |
useTableHeight(contentSelectors?, paginationSelectors?, distance?)
获取表格可用高度(自动减去分页器高度)。
const { height, getHeight } = useTableHeight("#data-table", "#custom-pagination", 20);参数:
| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| contentSelectors | string | '#data-table' | 内容元素选择器 |
| paginationSelectors | string | '#custom-pagination' | 分页器选择器 |
| distance | number | 0 | 额外距离 |
deviceDetection()
检测设备类型(纯函数式)。
const isMobile = deviceDetection();ElementHeightHelper
元素高度工具类。
// 获取元素距离顶部高度
const top = ElementHeightHelper.getFromTop("#element");
// 获取元素总高度(含 margin)
const height = ElementHeightHelper.getTotalHeight("#element");静态方法:
| 方法 | 返回值 | 说明 |
|------|--------|------|
| getFromTop(element) | number | 元素距离顶部高度 |
| getTotalHeight(element) | number | 元素总高度(含 margin) |
分页工具 (Pagination)
usePagination(pageSize?, options?)
创建分页配置。
const pagination = usePagination(10, {
showSizePicker: true,
size: "small",
});
console.log(pagination.currentPage); // 当前页
console.log(pagination.pageSize); // 每页条数
console.log(pagination.itemCount); // 总条数参数:
| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| pageSize | number | 10 | 每页条数 |
| options.showSizePicker | boolean | true | 是否显示分页选择器 |
| options.size | 'small' \| 'medium' \| 'large' | 'small' | 分页器尺寸 |
PaginationType 接口:
interface PaginationType {
currentPage: number; // 当前页
pageSize: number; // 每页条数
itemCount: number; // 总条数
showSizePicker: boolean; // 是否显示分页选择器
pageSizes: number[]; // 分页大小选项
size: "small" | "medium" | "large"; // 分页器尺寸
}响应式工具 (Model)
useModelBinding<T, K>(props, emit, propName)
创建双向绑定的 computed,适用于 v-model 场景。
// 在组件中使用
const modelValue = useModelBinding(props, emit, "modelValue");等价于:
computed({
get() {
return props.modelValue;
},
set(newVal) {
emit("update:modelValue", newVal);
},
});useVisibleBinding(props, emit)
创建 visible 双向绑定(常用于弹窗、抽屉等组件)。
const visible = useVisibleBinding(props, emit);useResetReactive<T>(value)
创建可重置的响应式状态。
const [state, reset] = useResetReactive({
name: "",
age: 0,
});
// 修改状态
state.name = "张三";
// 重置为初始值
reset();返回值:
| 属性 | 类型 | 说明 |
|------|------|------|
| state | Reactive<T> | 响应式状态对象 |
| reset | VoidFunction | 重置函数 |
useModalConfig<T>(defaultConfig)
创建弹窗配置(含打开/关闭逻辑)。
const [config, open, close] = useModalConfig({
visible: false,
title: "",
data: null,
});
open("visible"); // 打开弹窗
open("visible", { name: "张三" }); // 打开并传数据
close(); // 关闭弹窗并重置返回值:
| 属性 | 类型 | 说明 |
|------|------|------|
| config | Reactive<T> | 弹窗配置对象 |
| open | Function | 打开弹窗函数 |
| close | Function | 关闭弹窗函数 |
