Files
aphrodite/src/components/Stars/utils/url.ts
2025-03-22 00:01:11 +08:00

48 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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('&');
}