uniapp-h5/src/utils/utils.js

95 lines
3.0 KiB
JavaScript
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.

//获取url后面拼接的参数
export const getQueryString = (name) => {
let urlStr = window.location.href.split('?')[1]
const urlSearchParams = new URLSearchParams(urlStr)
const result = Object.fromEntries(urlSearchParams.entries())
return name ? result[name] : result
}
//是否iOS设备
export const isIOS = () => userAgent.indexOf('iPhone') > -1 || userAgent.indexOf('iPad') > -1;
//是否Android设备
export const isAndroid = () => userAgent.indexOf('Android') > -1;
export const deepClone = (source) => {
if (!source && typeof source !== "object") {
return source;
}
const targetObj = source.constructor === Array ? [] : {};
Object.keys(source).forEach((keys) => {
if (source[keys] && typeof source[keys] === "object") {
(targetObj)[keys] = deepClone(source[keys]);
} else {
(targetObj)[keys] = source[keys];
}
});
return targetObj;
}
/**
* @description 生成唯一 uuid
* @returns {String}
*/
export function generateUUID() {
let uuid = "";
for (let i = 0; i < 32; i++) {
let random = (Math.random() * 16) | 0;
if (i === 8 || i === 12 || i === 16 || i === 20) uuid += "-";
uuid += (i === 12 ? 4 : i === 16 ? (random & 3) | 8 : random).toString(16);
}
return uuid;
}
export function getQueryParams(url) {
// 若未传入URL则使用当前页面URL
const targetUrl = url || window.location.href;
// 用于存储查询参数的对象
const queryParams = {};
// 查找URL中问号的位置
const queryStart = targetUrl.indexOf('?');
// 如果URL中不存在问号说明没有查询参数
if (queryStart === -1) {
return queryParams;
}
// 提取查询字符串部分(不包含问号)
const queryString = targetUrl.substring(queryStart + 1);
// 查找查询字符串中哈希符号的位置
const hashIndex = queryString.indexOf('#');
// 移除哈希符号及其后面的内容
const cleanQuery = hashIndex !== -1 ? queryString.substring(0, hashIndex) : queryString;
// 如果查询字符串为空,直接返回空对象
if (!cleanQuery) {
return queryParams;
}
// 按"&"分割查询字符串为参数数组
const params = cleanQuery.split('&');
// 遍历参数数组
for (const param of params) {
// 按"="分割每个参数为键值对
const [key, value] = param.split('=');
if (key) {
// 对键和值进行URL解码
const decodedKey = decodeURIComponent(key);
const decodedValue = value !== undefined ? decodeURIComponent(value) : '';
// 处理重复参数名的情况,将其值存储为数组
if (queryParams.hasOwnProperty(decodedKey)) {
if (!Array.isArray(queryParams[decodedKey])) {
queryParams[decodedKey] = [queryParams[decodedKey]];
}
queryParams[decodedKey].push(decodedValue);
} else {
queryParams[decodedKey] = decodedValue;
}
}
}
return queryParams;
}