zxd-vue-utils
v1.0.1
Published
Vue3 工具类库,专为 UniApp 项目设计
Maintainers
Readme
zxd-vue-utils
🚀 Vue3 工具类库,专为 UniApp 项目设计
特性
- 📱 跨平台支持: 支持微信小程序、H5、APP 等多平台
- 🛠️ TypeScript: 完整的类型定义支持
- 🎯 Vue3 Composition API: 提供响应式组合函数
- 📦 模块化设计: 支持按需导入
- 🔧 开箱即用: 常用工具函数集合
- 🏗️ UniApp 优化: 针对 UniApp 项目特点优化
安装
# 使用 pnpm(推荐)
pnpm add zxd-vue-utils
# 使用 npm
npm install zxd-vue-utils
# 使用 yarn
yarn add zxd-vue-utils快速开始
完整导入
import QoderUtils from "zxd-vue-utils";
// 使用存储工具
QoderUtils.storage.setStorage("key", "value");
const value = QoderUtils.storage.getStorage("key");
// 使用网络请求
const response = await QoderUtils.request.http.get("/api/user");
// 使用通用工具
const id = QoderUtils.common.generateId();
const cloned = QoderUtils.common.deepClone(data);按需导入
import { setStorage, getStorage } from "zxd-vue-utils";
import { http } from "zxd-vue-utils";
import { useLoading, useRequest } from "zxd-vue-utils";
// 在 Vue 组件中使用
export default {
setup() {
const { loading, setLoading, withLoading } = useLoading();
const { data, loading: reqLoading, execute } = useRequest("/api/data");
return {
loading,
data,
reqLoading,
};
},
};主要模块
1. 存储工具 (Storage)
跨平台本地存储解决方案:
import { setStorage, getStorage, removeStorage } from "zxd-vue-utils";
// 基础存储
setStorage("user", { name: "John", age: 30 });
const user = getStorage("user");
// 带过期时间的存储
setStorage("token", "abc123", { expire: 24 * 60 * 60 * 1000 }); // 24小时后过期
// 加密存储
setStorage("sensitive", "data", { encrypt: true });2. 网络请求 (Request)
基于 UniApp 的网络请求封装:
import { http, HttpRequest } from "zxd-vue-utils";
// 创建请求实例
const api = new HttpRequest({
baseURL: "https://api.example.com",
timeout: 10000,
});
// 设置拦截器
api.setInterceptors({
request: (config) => {
config.header.Authorization = getStorage("token");
return config;
},
response: (response) => {
if (response.code !== 200) {
uni.showToast({ title: response.message, icon: "error" });
}
return response;
},
});
// 发起请求
const userList = await api.get("/users");
const createResult = await api.post("/users", { name: "John" });3. 通用工具 (Common)
常用的工具函数:
import {
debounce,
throttle,
deepClone,
generateId,
unique,
sortBy,
} from "zxd-vue-utils";
// 防抖和节流
const debouncedSearch = debounce(searchFunction, 300);
const throttledScroll = throttle(scrollFunction, 100);
// 深拷贝
const cloned = deepClone(originalObject);
// 数组处理
const uniqueArray = unique([1, 2, 2, 3, 3]);
const sorted = sortBy(userList, "age", "desc");4. 数据验证 (Validation)
表单验证和数据校验:
import {
isPhone,
isEmail,
isIdCard,
validateForm,
validatePassword,
} from "zxd-vue-utils";
// 单项验证
const isValid = isPhone("13812345678"); // true
const isValidEmail = isEmail("[email protected]"); // true
// 表单验证
const formData = { name: "", phone: "13812345678", email: "[email protected]" };
const rules = {
name: { required: true, min: 2, message: "姓名至少2个字符" },
phone: {
required: true,
pattern: /^1[3-9]\d{9}$/,
message: "手机号格式错误",
},
email: { required: true, validator: (value) => isEmail(value) },
};
const { valid, errors } = validateForm(formData, rules);5. 格式化工具 (Format)
数据格式化处理:
import {
formatDate,
formatFileSize,
formatCurrency,
maskPhone,
maskIdCard,
} from "zxd-vue-utils";
// 时间格式化
const dateStr = formatDate(new Date(), "YYYY-MM-DD HH:mm");
const relativeTime = formatRelativeTime(new Date(Date.now() - 3600000)); // "1小时前"
// 数据脱敏
const maskedPhone = maskPhone("13812345678"); // "138****5678"
const maskedCard = maskIdCard("123456789012345678"); // "123456********5678"
// 金额格式化
const price = formatCurrency(1234.56); // "¥1,234.56"6. Composition API
Vue 3 响应式组合函数:
import { useLoading, useRequest, usePagination } from "zxd-vue-utils";
export default {
setup() {
// 加载状态管理
const { loading, setLoading, withLoading } = useLoading();
// 请求管理
const {
data,
loading: reqLoading,
execute,
refresh,
} = useRequest("/api/users", {
immediate: true,
onSuccess: (data) => console.log("Success:", data),
onError: (error) => console.error("Error:", error),
});
// 分页请求
const {
data: pageData,
loading: pageLoading,
loadMore,
reset,
} = usePagination("/api/users", {
pageSize: 20,
});
return {
loading,
data,
pageData,
refresh,
loadMore,
};
},
};平台兼容性
| 平台 | 存储 | 请求 | 工具函数 | 格式化 | 验证 | | ------------ | ---- | ---- | -------- | ------ | ---- | | 微信小程序 | ✅ | ✅ | ✅ | ✅ | ✅ | | 支付宝小程序 | ✅ | ✅ | ✅ | ✅ | ✅ | | H5 | ✅ | ✅ | ✅ | ✅ | ✅ | | APP | ✅ | ✅ | ✅ | ✅ | ✅ |
TypeScript 支持
本库完全使用 TypeScript 编写,提供完整的类型定义:
import { ResponseData, UserInfo, PaginationResponse } from "zxd-vue-utils";
interface User {
id: number;
name: string;
email: string;
}
const response: ResponseData<User[]> = await http.get<User[]>("/users");配置
请求配置
import { http } from "zxd-vue-utils";
// 全局配置
http.setInterceptors({
request: (config) => {
// 添加认证头
const token = getStorage("token");
if (token) {
config.header.Authorization = `Bearer ${token}`;
}
return config;
},
response: (response) => {
// 统一错误处理
if (response.code !== 200) {
uni.showToast({
title: response.message || "请求失败",
icon: "error",
});
}
return response;
},
error: (error) => {
uni.showToast({
title: "网络错误",
icon: "error",
});
return Promise.reject(error);
},
});最佳实践
1. 在 UniApp 项目中使用
在 main.js 中全局配置:
import { createApp } from "vue";
import App from "./App.vue";
import { http } from "zxd-vue-utils";
// 配置请求基础URL
http.setInterceptors({
request: (config) => {
config.baseURL = "https://your-api.com";
return config;
},
});
const app = createApp(App);
app.mount("#app");2. 错误处理
import { useRequest } from "zxd-vue-utils";
export default {
setup() {
const { data, error, loading, execute } = useRequest("/api/data", {
immediate: false,
onError: (err) => {
// 统一错误处理
console.error("Request failed:", err);
uni.showToast({
title: "加载失败",
icon: "error",
});
},
});
return { data, error, loading, execute };
},
};更新日志
v1.0.0
- 🎉 初始版本发布
- ✨ 支持跨平台存储
- ✨ 网络请求封装
- ✨ 常用工具函数
- ✨ 数据验证工具
- ✨ 格式化工具
- ✨ Vue 3 Composition API
贡献
欢迎提交 Issue 和 Pull Request!
许可证
MIT License
