safe-function
封装常用 js 函数,在函数内部处理异常报错,从此远离满屏 try catch
轻量,包大小 2kb
好用,1 分钟上手
放心用,绝对安全
使用前
try {
let name = JSON.parse('{"name": "safe"}')
} catch (error) {
console.log(error)
}
try {
let urlObj = new URL(url);
} catch (error) {
console.log(error)
}使用后
import { jsonPrase, newURL } from 'safe-function'
let obj = jsonPrase('{"name": "safe"}')
let urlObj = newURL(url);CommonJS 格式:
const { newURL } = require('safe-function');
ES 模块格式:
import { newURL } from 'safe-function';
newURL(url: string, base?: string)
- 获取 url 字符串解析对象,替代 new URL()
- 返回:URL | {}
jsonPrase(text: string, reviver?)
- json 字符串转 json 对象,替代 JSON.parse()
- 返回:Object | null
jsonStringify(value: Object, replacer?, space?: number | string)
- json 对象转 json 字符串,替代 JSON.stringify()
- 返回:JSON 字符串
setLocal(key: string, value, errCB?: Function)
- 往 localStorage 写入数据,替代 localStorage.setItem()
- errCB 回调函数,当 localStorage 存储数据超过最大容量时执行
getLocal(key: string)
- 获取 localStorage 数据,替代 localStorage.getItem()
- 返回:Object | null
removeOneLocal(key: string)
- 清除某一个 key 的数据,替代 localStorage.removeItem()
removeAllLocal()
- 清空 localStorage 全部数据,替代 localStorage.clear()
removeArrayLocal(keys: string[])
- 清除指定数组 keys 的数据
getCptStyle(el: HTMLElement, att: string = '', after: string | null = null)
- 获取元素计算属性,替代 getComputedStyle()
- 返回:'' | Object | string
selectorOne(select)
- 获取指定选择器的单个元素,替代 document.querySelector()
- 返回:HTMLElement | null
selectorAll(select)
- 获取指定选择器的全部元素,替代 document.querySelectorAll()
- 返回:NodeListOf | []
insertEl(tag: string, content: string, id?: string)
- 往 body 插入带内容元素
isStandardTag(tagName: string)
- 判断当前浏览器是否支持标准标签
- 返回:boolean
domReady(callback: () => void)
- 当前页面 dom ready(DOMContentLoaded 或者已经 onload) 时触发 callback 函数