提供一些基础的工具方法,可以根据自己的需要增删。

is

创建src/utils/is/index.js,写入以下内容:

utils/is/index.js
const toString = Object.prototype.toString;

/**
* @description: 判断值是否未某个类型
*/
export function is(val, type) {
return toString.call(val) === `[object ${type}]`;
}

/**
* @description: 是否为函数
*/
export function isFunction(val) {
return is(val, 'Function') || is(val, 'AsyncFunction');
}

/**
* @description: 是否已定义
*/
export const isDef = (val) => {
return typeof val !== 'undefined';
};

export const isUnDef = (val) => {
return !isDef(val);
};
/**
* @description: 是否为对象
*/
export const isObject = (val) => {
return val !== null && is(val, 'Object');
};

/**
* @description: 是否为时间
*/
export function isDate(val) {
return is(val, 'Date');
}

/**
* @description: 是否为数值
*/
export function isNumber(val) {
return is(val, 'Number');
}

/**
* @description: 是否为AsyncFunction
*/
export function isAsyncFunction(val) {
return is(val, 'AsyncFunction');
}

/**
* @description: 是否为promise
*/
export function isPromise(val) {
return (
is(val, 'Promise') &&
isObject(val) &&
isFunction(val.then) &&
isFunction(val.catch)
);
}

/**
* @description: 是否为字符串
*/
export function isString(val) {
return is(val, 'String');
}

/**
* @description: 是否为boolean类型
*/
export function isBoolean(val) {
return is(val, 'Boolean');
}

/**
* @description: 是否为数组
*/
export function isArray(val) {
return val && Array.isArray(val);
}

/**
* @description: 是否客户端
*/
export const isClient = () => {
return typeof window !== 'undefined';
};

/**
* @description: 是否为浏览器
*/
export const isWindow = (val) => {
return typeof window !== 'undefined' && is(val, 'Window');
};

export const isElement = (val) => {
return isObject(val) && !!val.tagName;
};

export const isServer = typeof window === 'undefined';

// 是否为图片节点
export function isImageDom(o) {
return o && ['IMAGE', 'IMG'].includes(o.tagName);
}

export function isNull(val) {
return val === null;
}

export function isNullAndUnDef(val) {
return isUnDef(val) && isNull(val);
}

export function isNullOrUnDef(val) {
return isUnDef(val) || isNull(val);
}
/**
* 判断是否 url
* */
export function isUrl(url) {
return /^(http|https):\/\//g.test(url);
}

index

创建src/utils/index.js,写入以下内容:

utils/index.js
import { PageEnum } from '@/enums/pageEnum';
import { NIcon } from 'naive-ui';
import { h } from 'vue';
import { isObject } from './is';

/**
* render 图标
* */
export function renderIcon(icon) {
return () => h(NIcon, null, { default: () => h(icon) });
}
/**
* Sums the passed percentage to the R, G or B of a HEX color
* @param {string} color The color to change
* @param {number} amount The amount to change the color by
* @returns {string} The processed part of the color
*/
function addLight(color, amount) {
const cc = parseInt(color, 16) + amount;
const c = cc > 255 ? 255 : cc;
return c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`;
}

/**
* Lightens a 6 char HEX color according to the passed percentage
* @param {string} color The color to change
* @param {number} amount The amount to change the color by
* @returns {string} The processed color represented as HEX
*/
export function lighten(color, amount) {
color = color.indexOf('#') >= 0 ? color.substring(1, color.length) : color;
amount = Math.trunc((255 * amount) / 100);
return `#${addLight(color.substring(0, 2), amount)}${addLight(
color.substring(2, 4),
amount
)}${addLight(color.substring(4, 6), amount)}`;
}

export function deepMerge(src = {}, target = {}) {
let key;
for (key in target) {
src[key] = isObject(src[key])
? deepMerge(src[key], target[key])
: (src[key] = target[key]);
}
return src;
}

Storage

Storage提供CRUD本地缓存和Cookies的功能

创建src/utils/Storage.js,填入以下内容:

utils/Storage.js
// 默认缓存期限为7天
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;

export const createStorage = ({
prefixKey = '',
storage = localStorage,
} = {}) => {
// 本地缓存对象
function Storage() {
this.storage = storage;
this.prefixKey = prefixKey;
this.getKey = function (key) {
return `${this.prefixKey}${key}`.toUpperCase();
};
/**
* @description 设置缓存
* @param {string} key 缓存键
* @param {*} value 缓存值
* @param expire
*/
this.set = function (key, value, expire = DEFAULT_CACHE_TIME) {
const stringData = JSON.stringify({
value,
expire: expire != null ? new Date().getTime() + expire * 1000 : null,
});
this.storage.setItem(this.getKey(key), stringData);
};
/**
* 读取缓存
* @param {string} key 缓存键
* @param {*=} def 默认值
*/
this.get = function (key, def = null) {
const item = this.storage.getItem(this.getKey(key));
if (item) {
try {
const data = JSON.parse(item);
const { value, expire } = data;
// 在有效期内直接返回
if (expire === null || expire >= Date.now()) {
return value;
}
this.remove(key);
} catch (e) {
return def;
}
}
return def;
};
/**
* 从缓存删除某项
* @param {string} key
*/
this.remove = function (key) {
this.storage.removeItem(this.getKey(key));
};
/**
* 清空所有缓存
* @memberOf Cache
*/
this.clear = function () {
this.storage.clear();
};
/**
* 设置cookie
* @param {string} name cookie 名称
* @param {*} value cookie 值
* @param {number=} expire 过期时间
* 如果过期时间未设置,默认关闭浏览器自动删除
* @example
*/
this.setCookie = function (name, value, expire = DEFAULT_CACHE_TIME) {
document.cookie = `${this.getKey(name)}=${value}; Max-Age=${expire}`;
};
this.getCookie = function (name) {
const cookieArr = document.cookie.split('; ');
for (let i = 0, length = cookieArr.length; i < length; i++) {
const kv = cookieArr[i].split('=');
if (kv[0] === this.getKey(name)) {
return kv[1];
}
}
return '';
};
/**
* 根据名字删除指定的cookie
* @param {string} key
*/
this.removeCookie = function (key) {
this.setCookie(key, 1, -1);
};
/**
* 清空cookie,使所有cookie失效
*/
this.clearCookie = function () {
const keys = document.cookie.match(/[^ =;]+(?==)/g);
if (keys) {
for (let i = keys.length; i--; ) {
document.cookie = keys[i] + '=0;expire=' + new Date(0).toUTCString();
}
}
};
}
return new Storage();
};

export const storage = createStorage();

export default Storage;

urlUtils

当我们在使用POST请求是,可能需要将对象添加当作参数拼接到URL上面

创建src/utils/urlUtils.js,填入以下内容:

utils/urlUtils.js
/**
* 将对象添加当作参数拼接到URL上面
* @param baseUrl 需要拼接的url
* @param obj 参数对象
* @returns {string} 拼接后的对象
* 例子:
* let obj = {a: '3', b: '4'}
* setObjToUrlParams('www.baidu.com', obj)
* ==>www.baidu.com?a=3&b=4
*/
export function setObjToUrlParams(baseUrl, obj) {
let parameters = '';
let url = '';
for (const key in obj) {
parameters += key + '=' + encodeURIComponent(obj[key]) + '&';
}
parameters = parameters.replace(/&$/, '');
if (/\?$/.test(baseUrl)) {
url = baseUrl + parameters;
} else {
url = baseUrl.replace(/\/?$/, '?') + parameters;
}
return url;
}

工具方法远不止这些,后面会逐渐完善