Files
aphrodite/src/components/Stars/utils/url.ts

48 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-03-22 00:01:11 +08:00
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('&');
}