基础使用 #
环境准备 #
项目结构 #
text
project/
├── src/
│ ├── utils/
│ │ ├── index.js # 主入口
│ │ ├── url.js # URL 处理
│ │ ├── cookie.js # Cookie 操作
│ │ ├── date.js # 日期时间
│ │ ├── store.js # 本地存储
│ │ ├── file.js # 文件处理
│ │ ├── color.js # 颜色转换
│ │ ├── theme.js # 主题管理
│ │ ├── md5.js # MD5 加密
│ │ └── md6.js # MD6 加密
│ └── main.js
└── package.json
模块系统支持 #
javascript
import { getQueryString } from './utils';
const { getCookie } = require('./utils/cookie');
引入方式 #
1. 按需引入(推荐) #
javascript
import { getQueryString, getQueryParam } from './utils';
const id = getQueryString('id');
const params = getQueryParam(window.location.href);
2. 解构引入 #
javascript
import {
getQueryString,
getCookie,
setCookie,
formater,
formatFileSize
} from './utils';
3. 命名空间引入 #
javascript
import * as utils from './utils';
const id = utils.getQueryString('id');
const date = utils.formater(Date.now(), 'yyyy-MM-dd');
4. 默认导出引入 #
javascript
import store from './utils/store';
import md5 from './utils/md5';
import md6 from './utils/md6';
store.set('key', 'value');
const hash = md5('hello');
基本使用示例 #
URL 参数处理 #
javascript
import { getQueryString, getQueryParam, addQueryParam } from './utils';
const id = getQueryString('id');
console.log(id);
const params = getQueryParam('https://example.com?name=John&age=25');
console.log(params);
const newUrl = addQueryParam('https://example.com?page=1', { page: 2, size: 10 });
console.log(newUrl);
Cookie 操作 #
javascript
import { getCookie, setCookie, deleteCookie } from './utils/cookie';
setCookie('token', 'abc123xyz', 7);
setCookie('user', 'John', 30);
const token = getCookie('token');
console.log(token);
deleteCookie('token');
日期时间处理 #
javascript
import { formater, getTimeSpan, getTimeInfo } from './utils/date';
const now = Date.now();
console.log(formater(now, 'yyyy-MM-dd'));
console.log(formater(now, 'yyyy-MM-dd HH:mm:ss'));
console.log(formater(now, 'MM月dd日 hh:mm'));
const date1 = new Date('2026-04-01');
const date2 = new Date('2026-04-04');
console.log(getTimeSpan(date1, date2, 'd'));
const info = getTimeInfo(now);
console.log(info);
本地存储 #
javascript
import store from './utils/store';
store.set('user', { name: 'John', age: 25 });
const user = store.get('user');
console.log(user);
const tomorrow = Date.now() + 24 * 60 * 60 * 1000;
store.set('session', { token: 'abc123' }, tomorrow);
store.remove('user');
store.removeAll();
文件处理 #
javascript
import { formatFileSize, downloadFile, getFileUrl } from './utils';
console.log(formatFileSize(1024));
console.log(formatFileSize(1024 * 1024));
console.log(formatFileSize(1024 * 1024 * 1024));
downloadFile('https://example.com/file.pdf', 'document.pdf');
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
const url = getFileUrl(file);
console.log(url);
});
颜色转换 #
javascript
import { rgb2hex, hex2rgb } from './utils';
console.log(rgb2hex([255, 0, 0]));
console.log(rgb2hex([0, 128, 255]));
console.log(rgb2hex([255, 255, 0]));
console.log(hex2rgb('#ff0000'));
console.log(hex2rgb('#0080ff'));
console.log(hex2rgb('#ffff00'));
主题管理 #
javascript
import { getTheme, setTheme, toggleTheme, initTheme } from './utils/theme';
initTheme();
const currentTheme = getTheme();
console.log(currentTheme);
setTheme('dark');
const newTheme = toggleTheme();
console.log(newTheme);
加密哈希 #
javascript
import md5 from './utils/md5';
import md6 from './utils/md6';
console.log(md5('hello world'));
console.log(md6.hash128('hello world'));
console.log(md6.hash256('hello world'));
console.log(md6.hash512('hello world'));
工具函数详解 #
URL 处理函数 #
getQueryString(name) #
获取 URL 中指定参数的值。
javascript
import { getQueryString } from './utils';
const url = 'https://example.com?id=123&name=John';
window.location.search = '?id=123&name=John';
const id = getQueryString('id');
const name = getQueryString('name');
console.log(id);
console.log(name);
getQueryParam(url) #
获取 URL 中所有参数,返回对象。
javascript
import { getQueryParam } from './utils';
const url = 'https://example.com?id=123&name=John&age=25';
const params = getQueryParam(url);
console.log(params);
addQueryParam(url, param) #
向 URL 添加参数。
javascript
import { addQueryParam } from './utils';
const url = 'https://example.com?page=1';
const newUrl = addQueryParam(url, { page: 2, size: 10 });
console.log(newUrl);
Cookie 操作函数 #
setCookie(name, value, days) #
设置 Cookie。
javascript
import { setCookie } from './utils/cookie';
setCookie('token', 'abc123', 7);
setCookie('user', 'John', 30);
setCookie('preference', 'dark', 365);
getCookie(name) #
获取 Cookie 值。
javascript
import { getCookie } from './utils/cookie';
const token = getCookie('token');
const user = getCookie('user');
if (!token) {
console.log('用户未登录');
}
deleteCookie(name) #
删除 Cookie。
javascript
import { deleteCookie } from './utils/cookie';
deleteCookie('token');
deleteCookie('user');
日期时间函数 #
formater(time, format) #
格式化日期时间。
javascript
import { formater } from './utils/date';
const now = Date.now();
console.log(formater(now, 'yyyy-MM-dd'));
console.log(formater(now, 'yyyy/MM/dd'));
console.log(formater(now, 'yyyy-MM-dd HH:mm:ss'));
console.log(formater(now, 'MM月dd日 星期e'));
console.log(formater(now, 'hh:mm:ss'));
getTimeSpan(time1, time2, format) #
计算两个时间的间隔。
javascript
import { getTimeSpan } from './utils/date';
const date1 = new Date('2026-04-01');
const date2 = new Date('2026-04-04');
console.log(getTimeSpan(date1, date2, 's'));
console.log(getTimeSpan(date1, date2, 'm'));
console.log(getTimeSpan(date1, date2, 'h'));
console.log(getTimeSpan(date1, date2, 'd'));
getTimeInfo(time) #
获取时间的各个部分。
javascript
import { getTimeInfo } from './utils/date';
const info = getTimeInfo(Date.now());
console.log(info);
存储函数 #
store.get(key) #
获取本地存储数据。
javascript
import store from './utils/store';
const user = store.get('user');
const settings = store.get('settings');
store.set(key, value, expires) #
设置本地存储数据。
javascript
import store from './utils/store';
store.set('user', { name: 'John' });
const oneDay = Date.now() + 24 * 60 * 60 * 1000;
store.set('session', { token: 'abc' }, oneDay);
const oneWeek = Date.now() + 7 * 24 * 60 * 60 * 1000;
store.set('preference', { theme: 'dark' }, oneWeek);
store.remove(key) #
删除本地存储数据。
javascript
import store from './utils/store';
store.remove('user');
store.remove('session');
store.removeAll() #
清空所有本地存储。
javascript
import store from './utils/store';
store.removeAll();
错误处理 #
安全调用 #
javascript
import { getCookie, setCookie } from './utils/cookie';
const safeGetCookie = (name) => {
try {
return getCookie(name);
} catch (e) {
console.error('Cookie 读取失败:', e);
return null;
}
};
const safeSetCookie = (name, value, days) => {
try {
setCookie(name, value, days);
return true;
} catch (e) {
console.error('Cookie 设置失败:', e);
return false;
}
};
参数验证 #
javascript
import { formater } from './utils/date';
const safeFormatDate = (date, format = 'yyyy-MM-dd') => {
if (!date) return '';
const timestamp = new Date(date).getTime();
if (isNaN(timestamp)) {
console.warn('无效的日期:', date);
return '';
}
return formater(date, format);
};
最佳实践 #
1. 统一入口导出 #
javascript
export { getQueryString, getQueryParam, addQueryParam } from './url';
export { getCookie, setCookie, deleteCookie } from './cookie';
export { formater, getTimeSpan, getTimeInfo } from './date';
export { default as store } from './store';
export { formatFileSize, downloadFile, getImageBase64 } from './file';
2. 类型注释 #
javascript
/**
* 获取 URL 参数
* @param {string} name - 参数名
* @returns {string} 参数值
*/
export const getQueryString = (name) => {
const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
const r = window.location.search.slice(1).match(reg);
if (r != null) {
return decodeURIComponent(r[2]);
}
return '';
};
3. 默认参数 #
javascript
export const formater = (time, format = 'yyyy-MM-dd HH:mm:ss') => {
const timeInfo = getTimeInfo(time);
if (!timeInfo) return '';
return format
.replace(/yyyy/, timeInfo.yyyy)
.replace(/MM/, timeInfo.MM)
.replace(/dd/, timeInfo.dd)
.replace(/HH/, timeInfo.HH)
.replace(/mm/, timeInfo.mm)
.replace(/ss/, timeInfo.ss);
};
下一步 #
现在你已经掌握了基础使用方法,接下来学习 URL 参数处理,深入了解 URL 操作的详细用法!
最后更新:2026-04-04