luoyu-core
v0.0.4
Published
工具包-封装一些常用的方法与api请求
Maintainers
Readme
我需要先查看src/packages/index.ts文件的内容,了解当前项目导出了哪些方法和对象,以便为它们编写使用示例文档。
toolName: view_files
status: success
filePath: e:\project\code\npm\luoyu-core\src\packages\index.ts
现在我需要查看src/packages/utils目录下的index.ts文件,了解具体导出了哪些工具方法和对象,以便为它们编写详细的使用示例。
toolName: view_files
status: success
filePath: e:\project\code\npm\luoyu-core\src\packages\utils\index.ts
现在我需要查看各个工具模块的具体内容,以便了解它们导出的方法和功能。我会先查看几个核心模块,如array、string、number等。
toolName: view_files
status: success
filePath: e:\project\code\npm\luoyu-core\src\packages\utils\array.ts e:\project\code\npm\luoyu-core\src\packages\utils\string.ts e:\project\code\npm\luoyu-core\src\packages\utils\number.ts
我需要继续查看剩余的工具模块文件,以便全面了解所有导出的方法和功能,为它们编写详细的使用示例文档。
toolName: view_files
status: success
filePath: e:\project\code\npm\luoyu-core\src\packages\utils\cloud.ts e:\project\code\npm\luoyu-core\src\packages\utils\time\index.ts e:\project\code\npm\luoyu-core\src\packages\utils\request.ts
我需要继续查看剩余的工具模块,以便全面了解所有导出的方法和功能,为编写完整的使用示例文档做准备。
toolName: view_files
status: success
filePath: e:\project\code\npm\luoyu-core\src\packages\utils\storage.ts e:\project\code\npm\luoyu-core\src\packages\utils\fetch.ts e:\project\code\npm\luoyu-core\src\packages\utils\date.ts
我需要继续查看剩余的工具模块,以便全面了解所有导出的方法和功能,为编写完整的使用示例文档做准备。
toolName: view_files
status: success
filePath: e:\project\code\npm\luoyu-core\src\packages\utils\file.ts e:\project\code\npm\luoyu-core\src\packages\utils\xlsx.ts e:\project\code\npm\luoyu-core\src\packages\utils\color.ts
我需要继续查看剩余的工具模块,以便全面了解所有导出的方法和功能,为编写完整的使用示例文档做准备。
toolName: view_files
status: success
filePath: e:\project\code\npm\luoyu-core\src\packages\utils\format.ts e:\project\code\npm\luoyu-core\src\packages\utils\is.ts e:\project\code\npm\luoyu-core\src\packages\utils\performance.ts
我需要继续查看剩余的工具模块,以便全面了解所有导出的方法和功能,为编写完整的使用示例文档做准备。
toolName: view_files
status: success
filePath: e:\project\code\npm\luoyu-core\src\packages\utils\uuid.ts e:\project\code\npm\luoyu-core\src\packages\utils\pixel.ts e:\project\code\npm\luoyu-core\src\packages\utils\interval.ts
# luoyu-core 使用示例文档
## 1. 安装和引入
### 安装
```bash
npm install luoyu-core引入
// 作为插件使用
import luoyuCore from 'luoyu-core';
// 或按需引入
import { unique, formatPhoneNumber, CloudApi } from 'luoyu-core';2. Array 工具
parseTreeToArray - 解析树形数据为普通数组
import { parseTreeToArray } from 'luoyu-core';
// 示例数据
const treeData = [
{
id: 1,
name: '部门1',
children: [
{ id: 11, name: '子部门11' },
{ id: 12, name: '子部门12' }
]
},
{ id: 2, name: '部门2' }
];
// 使用
const flatArray = parseTreeToArray(treeData);
console.log(flatArray);
// 输出: [{id: 1, name: '部门1'}, {id: 11, name: '子部门11'}, {id: 12, name: '子部门12'}, {id: 2, name: '部门2'}]checkSumEqualsTarget - 检查数组和是否等于目标值
import { checkSumEqualsTarget } from 'luoyu-core';
// 使用
const numbers = [1, 2, 3, 4];
const target = 10;
const result = checkSumEqualsTarget(numbers, target);
console.log(result); // 输出: trueuniqueObj - 对象数组去重
import { uniqueObj } from 'luoyu-core';
// 示例数据
const data = [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' },
{ id: 1, name: '张三' }
];
// 使用
const uniqueData = uniqueObj(data, 'id');
console.log(uniqueData);
// 输出: [{id: 1, name: '张三'}, {id: 2, name: '李四'}]buildTree - 构建树形数据
import { buildTree } from 'luoyu-core';
// 示例数据
const data = [
{ id: 1, name: '部门1', parentId: 0 },
{ id: 2, name: '部门2', parentId: 0 },
{ id: 11, name: '子部门11', parentId: 1 },
{ id: 12, name: '子部门12', parentId: 1 }
];
// 使用
const treeData = buildTree(data);
console.log(treeData);unique - 普通数组去重
import { unique } from 'luoyu-core';
// 使用
const arr = [1, 2, 3, 2, 1];
const uniqueArr = unique(arr);
console.log(uniqueArr); // 输出: [1, 2, 3]getPages - 获取总页数
import { getPages } from 'luoyu-core';
// 使用
const totalItems = 25;
const pageSize = 10;
const pages = getPages(totalItems, pageSize);
console.log(pages); // 输出: 3getPaginateData - 获取分页数据
import { getPaginateData } from 'luoyu-core';
// 示例数据
const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// 使用
async function getPageData() {
const result = await getPaginateData(data, 2, 3);
console.log(result);
// 输出: { rows: [4, 5, 6], total: 4, currentPage: 2, pageSize: 3 }
}
getPageData();3. String 工具
formatPhoneNumber - 格式化手机号码
import { formatPhoneNumber } from 'luoyu-core';
// 使用
const phone = '13812345678';
const formattedPhone = formatPhoneNumber(phone);
console.log(formattedPhone); // 输出: 138****5678extractAttributes - 提取字符串中的属性
import { extractAttributes } from 'luoyu-core';
// 使用
const str = '用户{name}的年龄是[age]岁';
const attributes = extractAttributes(str);
console.log(attributes); // 输出: ['name', 'age']copyContent - 复制内容到剪贴板
import { copyContent } from 'luoyu-core';
// 使用
copyContent('这是要复制的内容');
// 内容已复制到剪贴板extractAttributesToFormat - 提取指定格式的属性
import { extractAttributesToFormat } from 'luoyu-core';
// 使用
const str = '用户{name}的年龄是[age]岁,身高为data.height厘米';
// 提取{}格式的属性
const bracesAttrs = extractAttributesToFormat(str, 'braces');
console.log(bracesAttrs); // 输出: ['name']
// 提取[]格式的属性
const bracketsAttrs = extractAttributesToFormat(str, 'brackets');
console.log(bracketsAttrs); // 输出: ['age']
// 提取data.xxx格式的属性
const dotAttrs = extractAttributesToFormat(str, 'dot');
console.log(dotAttrs); // 输出: ['height']4. Number 工具
pea - 价格完整显示
import { pea } from 'luoyu-core';
// 使用
const price = 1234.5;
const formattedPrice = pea(price);
console.log(formattedPrice); // 输出: 1,234.50pe - 价格简化显示
import { pe } from 'luoyu-core';
// 使用
const price = '1234.50';
const simplifiedPrice = pe(price);
console.log(simplifiedPrice); // 输出: 1,234.5distance - 距离格式化
import { distance } from 'luoyu-core';
// 使用
const meters = 1500;
const formattedDistance = distance(meters);
console.log(formattedDistance); // 输出: 1.5km
// 仅显示数字
const distanceNumber = distance(meters, true);
console.log(distanceNumber); // 输出: 1.5algorithm - 经纬度计算距离
import { algorithm } from 'luoyu-core';
// 使用
const point1 = [27.83180, 113.08514]; // [纬度, 经度]
const point2 = [27.84180, 113.09514];
const distance = algorithm(point1, point2);
console.log(distance); // 输出: 距离(米)rad - 角度转换成弧度
import { rad } from 'luoyu-core';
// 使用
const degrees = 45;
const radians = rad(degrees);
console.log(radians); // 输出: 0.78539816339744835. Cloud API
CloudApi - 云函数API
import { CloudApi } from 'luoyu-core';
// 初始化
const cloudApi = new CloudApi({
baseUrl: 'https://api.example.com',
token: 'your-token',
headers: {
'Custom-Header': 'value'
}
});
// 调用云函数
async function callFunction() {
try {
const result = await cloudApi.callFunction('getUserInfo', { userId: 123 });
console.log(result);
} catch (error) {
console.error(error);
}
}
// 上传文件
async function uploadFile() {
try {
const file = new File(['content'], 'test.txt', { type: 'text/plain' });
const result = await cloudApi.uploadFile(file, 'upload/test.txt');
console.log(result);
} catch (error) {
console.error(error);
}
}
// 下载文件
async function downloadFile() {
try {
const result = await cloudApi.downloadFile('file-id-123');
console.log(result.tempFilePath);
} catch (error) {
console.error(error);
}
}
// 删除文件
async function deleteFile() {
try {
const result = await cloudApi.deleteFile(['file-id-123', 'file-id-456']);
console.log(result.deleted);
} catch (error) {
console.error(error);
}
}
// 上传base64文件
async function uploadBase64() {
try {
const base64 = 'base64-string';
const result = await cloudApi.upload(base64, 'test.txt');
console.log(result);
} catch (error) {
console.error(error);
}
}6. Time 工具
TimeExecutor - 全局定时器
import { TimeExecutor } from 'luoyu-core';
// 初始化全局定时器
const timerId = TimeExecutor.initTimer(true);
console.log(timerId); // 输出: 定时器ID
// 停止全局定时器
TimeExecutor.initTimer(false);TimeTask - 定时任务
import { TimeTask } from 'luoyu-core';
// 创建定时任务
const task = new TimeTask({
second: 10, // 每10秒执行一次
immediate: true, // 立即执行
func: () => {
console.log('定时任务执行了');
}
});
// 暂停执行
task.pause();
// 继续执行
task.play();
// 手动执行
task.exec();
// 关闭监听
task.off();
// 开启监听
task.on();
// 销毁任务
task.destroy();7. Request 工具
request - 创建axios实例
import { request } from 'luoyu-core';
// 创建请求实例
const api = request({
baseURL: 'https://api.example.com',
timeout: 10000,
interceptors: {
requestInterceptor: (config) => {
// 请求拦截处理
return config;
},
responseInterceptor: (res) => {
// 响应拦截处理
return res;
}
}
});
// 使用
async function fetchData() {
try {
const result = await api.get('/data');
console.log(result);
} catch (error) {
console.error(error);
}
}8. Storage 工具
Storage - 本地存储
import { Storage } from 'luoyu-core';
// 设置缓存
Storage.set('user', { name: '张三', age: 25 });
// 获取缓存
const user = Storage.get('user');
console.log(user); // 输出: { name: '张三', age: 25 }
// 使用sessionStorage
Storage.set('sessionKey', 'sessionValue', 'sessionStorage');
const sessionValue = Storage.get('sessionKey', 'sessionStorage');
console.log(sessionValue); // 输出: sessionValue
// 删除缓存
Storage.remove('user');9. Fetch 工具
HttpService - HTTP请求服务
import { HttpService, http } from 'luoyu-core';
// 创建HTTP服务实例
const httpService = new HttpService({
requestInterceptor: (config) => {
// 请求拦截处理
config.headers = {
...config.headers,
'Authorization': 'Bearer token'
};
return config;
},
responseInterceptor: (response) => {
// 响应拦截处理
if (!response.ok) {
throw new Error('请求失败');
}
return response;
}
});
// 或使用简化创建方式
const httpService2 = http({
// 配置...
});
// 发起GET请求
async function fetchData() {
try {
const { id, data } = await httpService.get('https://api.example.com/users');
console.log('请求ID:', id);
console.log('数据:', data);
} catch (error) {
console.error(error);
}
}
// 发起POST请求
async function createUser() {
try {
const { id, data } = await httpService.post('https://api.example.com/users', {
name: '张三',
age: 25
});
console.log('创建成功:', data);
} catch (error) {
console.error(error);
}
}
// 取消请求
async function fetchWithCancel() {
try {
const { id, data } = await httpService.get('https://api.example.com/long-request');
console.log(data);
} catch (error) {
if (error.name === 'AbortError') {
console.log('请求已取消');
}
}
}
// 获取待处理请求
const pendingRequests = httpService.getPendingRequestIds();
console.log(pendingRequests);
// 取消所有请求
httpService.cancelAllRequests();10. Date 工具
getDaysInCurrentMonth - 获取当月天数
import { getDaysInCurrentMonth } from 'luoyu-core';
// 使用
const days = getDaysInCurrentMonth();
console.log(days); // 输出: 当前月份的天数
// 指定日期
const daysOfSpecifiedMonth = getDaysInCurrentMonth('2023-02-01');
console.log(daysOfSpecifiedMonth); // 输出: 28getWeekDates - 获取一周的日期列表
import { getWeekDates } from 'luoyu-core';
// 使用
const weekDates = getWeekDates();
console.log(weekDates); // 输出: ['2023-09-03', '2023-09-04', ..., '2023-09-09']
// 指定日期
const weekOfSpecifiedDate = getWeekDates(new Date('2023-01-01'));
console.log(weekOfSpecifiedDate);calculateTimeInterval - 计算时间区间
import { calculateTimeInterval } from 'luoyu-core';
// 使用
const start = '2023-01-01 10:00:00';
const end = '2023-01-02 11:30:45';
const interval = calculateTimeInterval(start, end);
console.log(interval);
// 输出: { years: 0, months: 0, days: 1, hours: 1, minutes: 30, seconds: 45 }11. File 工具
FileUtil - 文件处理
import { FileUtil } from 'luoyu-core';
// 下载Excel文件
const excelBlob = new Blob(['excel-content'], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
FileUtil.getExcel(excelBlob, '数据导出');
// 下载CSV文件
const csvBlob = new Blob(['csv-content'], { type: 'text/csv' });
FileUtil.getCsv(csvBlob, '数据导出');
// 统一下载
FileUtil.download('https://example.com/file.txt', '下载文件.txt');
// 通过URL下载文件
async function downloadFromUrl() {
await FileUtil.downloadFile('https://example.com/image.jpg', '图片.jpg');
}
// 字节转换
const arrayBuffer = FileUtil.s2ToArrayBuffer('test');
console.log(arrayBuffer);
// 读取文件内容
async function readFileContent() {
const file = new File(['content'], 'test.txt', { type: 'text/plain' });
const content = await FileUtil.readAsText(file);
console.log(content);
}
// 获取文件类型
const fileTypes = FileUtil.getFileTypes();
console.log(fileTypes);12. XLSX 工具
readFile - 读取XLSX文件
import { readFile } from 'luoyu-core';
// 使用
async function importExcel() {
const fileInput = document.querySelector('input[type="file"]');
if (fileInput.files && fileInput.files[0]) {
const data = await readFile(fileInput.files[0]);
console.log(data);
// 输出: [{ name: '工作表1', data: [/* 数据 */] }]
}
}exportXlsx - 导出XLSX文件
import { exportXlsx } from 'luoyu-core';
// 使用
const data = [
{ id: 1, name: '张三', age: 25 },
{ id: 2, name: '李四', age: 30 }
];
const fields = { id: 'ID', name: '姓名', age: '年龄' };
exportXlsx({
data,
fields,
filename: '用户数据'
});13. Color 工具
rgbaToHex - RGBA转HEX
import { rgbaToHex } from 'luoyu-core';
// 使用
const rgba = 'rgba(255, 0, 0, 0.5)';
const hex = rgbaToHex(rgba);
console.log(hex); // 输出: #ff000080rgbToHex - RGB转HEX
import { rgbToHex } from 'luoyu-core';
// 使用
const rgb = 'rgb(255, 0, 0)';
const hex = rgbToHex(rgb);
console.log(hex); // 输出: #ff0000colorToRgba - HEX转RGBA
import { colorToRgba } from 'luoyu-core';
// 使用
const hex = '#ff0000';
const rgba = colorToRgba(hex, 0.5);
console.log(rgba); // 输出: rgba(255, 0, 0, 0.5)14. Format 工具
countdown - 倒计时
import { countdown } from 'luoyu-core';
// 使用
countdown(10, (seconds) => {
console.log(`倒计时: ${seconds}秒`);
if (seconds === 0) {
console.log('倒计时结束');
}
});
// 输出: 倒计时: 10秒, 倒计时: 9秒, ..., 倒计时: 0秒, 倒计时结束percentageToPx - 百分比转像素
import { percentageToPx } from 'luoyu-core';
// 使用
const px = percentageToPx(50); // 视口高度的50%
console.log(px); // 输出: 540 (假设视口高度为1080px)
// 指定容器高度
const containerHeight = 500;
const px2 = percentageToPx('75%', containerHeight);
console.log(px2); // 输出: 375getType - 获取文件类型
import { getType } from 'luoyu-core';
// 使用
const type = getType('document.pdf');
console.log(type); // 输出: pdfbytesToSize - 字节大小转换
import { bytesToSize } from 'luoyu-core';
// 使用
const size = bytesToSize(1024 * 1024 * 5);
console.log(size); // 输出: 5MBtansParams - 参数转URL查询字符串
import { tansParams } from 'luoyu-core';
// 使用
const params = {
name: '张三',
age: 25,
address: {
city: '北京',
district: '朝阳区'
}
};
const queryString = tansParams(params);
console.log(queryString);
// 输出: name=张三&age=25&address[city]=北京&address[district]=朝阳区&15. Is 工具
isHttpUrl - 判断是否为HTTP URL
import { isHttpUrl } from 'luoyu-core';
// 使用
console.log(isHttpUrl('https://example.com')); // 输出: true
console.log(isHttpUrl('ftp://example.com')); // 输出: falseisDecimal - 判断是否为小数
import { isDecimal } from 'luoyu-core';
// 使用
console.log(isDecimal('123.45')); // 输出: true
console.log(isDecimal('123')); // 输出: falseisPercentage - 判断是否为百分比
import { isPercentage } from 'luoyu-core';
// 使用
console.log(isPercentage('50')); // 输出: true
console.log(isPercentage('50%', true)); // 输出: true
console.log(isPercentage('50%')); // 输出: false (默认不包含%)isValidTextObj - 判断是否为有效文本对象
import { isValidTextObj } from 'luoyu-core';
// 使用
console.log(isValidTextObj('{"name": "张三", "age": 25}')); // 输出: true
console.log(isValidTextObj('这不是一个对象')); // 输出: false16. Performance 工具
throttle - 节流函数
import { throttle } from 'luoyu-core';
// 使用
const throttledFn = throttle(() => {
console.log('节流函数执行了');
}, 1000);
// 连续调用,但每秒只执行一次
throttledFn();
throttledFn();
throttledFn();
// 输出: 节流函数执行了 (1秒后)debounce - 防抖函数
import { debounce } from 'luoyu-core';
// 使用
const debouncedFn = debounce(() => {
console.log('防抖函数执行了');
}, 1000);
// 连续调用,只在最后一次调用后1秒执行
debouncedFn();
debouncedFn();
debouncedFn();
// 输出: 防抖函数执行了 (1秒后)17. UUID 工具
buildUUID - 生成UUID
import { buildUUID } from 'luoyu-core';
// 使用
const uuid = buildUUID();
console.log(uuid); // 输出: 随机生成的UUID字符串buildShortUUID - 生成短UUID
import { buildShortUUID } from 'luoyu-core';
// 使用
const shortUUID = buildShortUUID('prefix');
console.log(shortUUID); // 输出: prefix_随机数+时间戳18. Pixel 工具
pxToRem - PX转REM
import { pxToRem } from 'luoyu-core';
// 使用
const rem = pxToRem(32);
console.log(rem); // 输出: 2rem (默认1rem=16px)
// 自定义基准值
const rem2 = pxToRem(32, 20);
console.log(rem2); // 输出: 1.6remremToPx - REM转PX
import { remToPx } from 'luoyu-core';
// 使用
const px = remToPx(2);
console.log(px); // 输出: 32px (默认1rem=16px)
// 自定义基准值
const px2 = remToPx(2, 20);
console.log(px2); // 输出: 40pxgetId - 生成唯一标识符
import { getId } from 'luoyu-core';
// 使用
const id = getId();
console.log(id); // 输出: pixel_随机字符串19. Interval 工具
rewriteInterval - 重写间隔执行函数
import { rewriteInterval } from 'luoyu-core';
// 使用
const interval = rewriteInterval(() => {
console.log('间隔执行函数');
}, 2000); // 每2秒执行一次
// 停止执行
interval.stop();20. 综合示例
Vue组件中使用示例
<template>
<div>
<h1>用户列表</h1>
<input v-model="searchKeyword" placeholder="搜索用户" />
<button @click="fetchUsers">获取用户列表</button>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>手机号码</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="user in paginatedData.rows" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.age }}</td>
<td>{{ formattedPhone(user.phone) }}</td>
<td>
<button @click="copyUserInfo(user)">复制用户信息</button>
</td>
</tr>
</tbody>
</table>
<div class="pagination">
<button @click="changePage(1)" :disabled="paginatedData.currentPage === 1">首页</button>
<button @click="changePage(paginatedData.currentPage - 1)" :disabled="paginatedData.currentPage === 1">上一页</button>
<span>{{ paginatedData.currentPage }} / {{ paginatedData.total }}</span>
<button @click="changePage(paginatedData.currentPage + 1)" :disabled="paginatedData.currentPage === paginatedData.total">下一页</button>
<button @click="changePage(paginatedData.total)" :disabled="paginatedData.currentPage === paginatedData.total">末页</button>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue';
import {
formatPhoneNumber,
copyContent,
getPaginateData,
throttle,
debounce
} from 'luoyu-core';
const searchKeyword = ref('');
const users = ref([]);
const paginatedData = ref({ rows: [], total: 0, currentPage: 1, pageSize: 10 });
// 格式化手机号码
const formattedPhone = (phone) => {
return formatPhoneNumber(phone);
};
// 复制用户信息
const copyUserInfo = (user) => {
copyContent(`用户:${user.name},ID:${user.id},年龄:${user.age}`);
alert('用户信息已复制到剪贴板');
};
// 获取用户列表
const fetchUsers = async () => {
// 模拟API请求
const mockUsers = Array.from({ length: 100 }, (_, i) => ({
id: i + 1,
name: `用户${i + 1}`,
age: 18 + Math.floor(Math.random() * 30),
phone: `138${Math.floor(Math.random() * 100000000)}`
}));
users.value = mockUsers;
// 分页
await updatePagination(1);
};
// 更新分页
const updatePagination = async (page) => {
const result = await getPaginateData(users.value, page, 10);
paginatedData.value = result;
};
// 切换页码
const changePage = (page) => {
updatePagination(page);
};
// 节流搜索
const throttledSearch = throttle(() => {
console.log('搜索:', searchKeyword.value);
// 执行搜索逻辑
}, 500);
// 防抖搜索
const debouncedSearch = debounce(() => {
console.log('搜索:', searchKeyword.value);
// 执行搜索逻辑
}, 1000);
// 组件挂载时获取数据
onMounted(() => {
fetchUsers();
});
</script>
<style scoped>
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 10px;
padding: 5px 10px;
}
</style>21. 总结
本文档详细介绍了 luoyu-core 库中所有导出方法和类的使用示例,包括:
- Array 工具:数组处理、树形结构转换、分页等
- String 工具:字符串格式化、属性提取、剪贴板操作等
- Number 工具:数字格式化、距离计算、经纬度处理等
- Cloud API:云函数调用、文件上传下载等
- Time 工具:全局定时器、定时任务管理等
- Request 工具:HTTP请求封装
- Storage 工具:本地存储操作
- Fetch 工具:增强型Fetch API
- Date 工具:日期处理、时间区间计算等
- File 工具:文件下载、读取、转换等
- XLSX 工具:Excel文件导入导出
- Color 工具:颜色格式转换
- Format 工具:数据格式化、参数转换等
- Is 工具:类型判断
- Performance 工具:节流、防抖等性能优化
- UUID 工具:唯一标识符生成
- Pixel 工具:像素单位转换
- Interval 工具:间隔执行函数
