48 lines
1.4 KiB
TypeScript
48 lines
1.4 KiB
TypeScript
import { RecordType } from '../interface';
|
||
|
||
/**
|
||
* 获取URL参数信息
|
||
* @param url 可选,指定URL,不传则使用当前页面URL
|
||
* @returns URL参数信息对象
|
||
*/
|
||
export const getUrlParams = (url?: string): RecordType => {
|
||
const query = url ? url : window.location.href;
|
||
const urlSearchParams = new URLSearchParams(query.split('?')[1] || '');
|
||
const result: RecordType = {};
|
||
|
||
urlSearchParams.forEach((value, key) => {
|
||
result[key] = value;
|
||
});
|
||
|
||
return result;
|
||
};
|
||
|
||
/**
|
||
* 将对象转换为 URL 查询字符串
|
||
* @param obj 要转换的对象
|
||
* @returns URL 查询字符串
|
||
*/
|
||
export function stringify(obj: Record<string, any>): string {
|
||
return Object.keys(obj)
|
||
.map((key) => {
|
||
const value = obj[key];
|
||
if (value === null || value === undefined) {
|
||
return '';
|
||
}
|
||
// 处理数组和嵌套对象
|
||
if (Array.isArray(value)) {
|
||
return value.map((v, i) => `${encodeURIComponent(key)}[${i}]=${encodeURIComponent(v)}`).join('&');
|
||
}
|
||
if (typeof value === 'object') {
|
||
return Object.keys(value)
|
||
.map(
|
||
(subKey) =>
|
||
`${encodeURIComponent(key)}[${encodeURIComponent(subKey)}]=${encodeURIComponent(value[subKey])}`,
|
||
)
|
||
.join('&');
|
||
}
|
||
return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
|
||
})
|
||
.filter(Boolean) // 过滤空值
|
||
.join('&');
|
||
}
|