常用的工具方法的封装
Posted langqq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常用的工具方法的封装相关的知识,希望对你有一定的参考价值。
import {Fecth} from ‘@/assets/js/http‘
import {codeState} from ‘@/assets/js/code‘
/****************************
*hasClass
*
* 判断是否存在某个class
* obj:原生dom
* className:要验证的class
*
* 返回:boolean,true 包含,false 不包含
*/
export const hasClass = function (obj, className) {
var reg = new RegExp(‘^|\\s‘ + className + ‘$|\\s‘)
return reg.test(obj.className)
}
/****************************
*addClass
*
* 添加一个class
* obj:原生dom
* className:要添加的class
*
* 返回:string,拼接在一起的className
*/
export const addClass = function (obj, className) {
if (hasClass(obj, className)) {
return
}
let classArr
let classNew
classArr = obj.className.split(‘ ‘)
classArr.push(className)
classNew = classArr.join(‘ ‘)
obj.className = classNew
}
/***************************
* ajax
*
* url:请求路径
* type:请求方式
* data:参数
* success:成功回调
* error:错误回调
*/
export const ajax = function (args) {
var opt = {
url: ‘‘,
type: ‘GET‘,
data: {},
success: function () {},
error: function () {}
}
extend(opt, args)
if (typeof opt.url === ‘string‘ && opt.url) {
let url = opt.url
let type = opt.type.toUpperCase()
let data = opt.data
let success = opt.success
let error = opt.error
let res
let xhr = XMLHttpRequest ? new XMLHttpRequest() : window.ActiveXObject(‘Miscrosoft.XMLHTTP‘)
let combinedUrl = dataToUri(url, data)
if (type === ‘GET‘) {
xhr.open(type, combinedUrl, true)
xhr.send()
}
if (type === ‘post‘) {
xhr.open(type, url, true)
xhr.setRequestHeader(‘Content-type‘, ‘application/x-www-form-urlencode‘)
xhr.send(combinedUrl)
}
xhr.onload = function () {
if (xhr.status === 200 || xhr.status === 304) {
res = xhr.responseText
if (success instanceof Function) {
success.call(xhr, res)
}
} else {
if (error instanceof Function) {
error.call(xhr, res)
}
}
}
}
}
/********************************
* jsonp
*
* url:请求路径
* data:参数
*/
export const jsonp = function (args) {
let opt = {
url: ‘‘,
data: {},
jsonpCallback: ‘jsonp‘
}
extend(opt, args)
let url = dataToUri(opt.url, opt.data) + encodeURIComponent(‘jsonpCallback‘) + ‘=‘ + encodeURIComponent(opt.jsonpCallback)
createScript({src: url})
}
/********************************
* dataToUri
*
* 将json格式的data和url合并在一起,并encode
* url: 标准url
* data: 必须是字面量对象格式
* encode: bollean格式,true 需要转译,false 不需要转译
*/
export const dataToUri = function (url, data, encode) {
// 是否为字面量对象
if (isJson(data)) {
let _encode = true
let dataArr = []
if (typeof encode === ‘boolean‘) {
_encode = encode
}
for (let item in data) {
let str = _encode ? (encodeURIComponent(item) + ‘=‘ + encodeURIComponent(data[item])) : item + ‘=‘ + data[item]
dataArr.push(str)
}
url += (url.indexOf(‘?‘) < 0 ? ‘?‘ : ‘&‘) + dataArr.join(‘&‘)
return url.replace(/$\\?/g, ‘‘)
} else {
return url
}
}
/********************************
* 参数的覆盖
* 以第一个为基准,并不新添属性
*/
export const extend = function (opt, args) {
for (let item in opt) {
if (args[item] !== undefined) {
opt[item] = args[item]
}
}
}
/*******************************
* 创建script标签
*
* opt为字面量对象,设置script的属性,
* 最终在head上创建一个script标签
*/
export const createScript = function (opt) {
let script = document.createElement(‘script‘)
// 是否为字面量对象
if (!isJson(opt)) {
return
}
for (let item in opt) {
script.setAttribute(item, opt[item])
}
document.querySelector(‘head‘).appendChild(script)
}
/********************************
* 判断是字面量对象
*
* true 是字面量对象, false 不是
*/
export const isJson = function (data) {
if (data instanceof Object && data.prototype === undefined) {
return true
}
return false
}
/*********************************************************************************************************************
* COOKIE 操作类
*/
/******************************
* 添加一个cookie
*/
export const setCookie = function (key, value, days) {
let Days = days || 30
let exp = new Date()
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
document.cookie = key + ‘=‘ + escape(value) + ‘;expires=‘ + exp.toGMTString()
}
/*******************************
* 获取某个cookie的值
*/
export const getCookie = function (key) {
let allcookies = document.cookie
let arr = allcookies.split(‘;‘)
let value
for (let i = 0; i < arr.length; i++) {
let strIn = arr[i]
let pos = strIn.indexOf(‘=‘)
let regEx = /\s+/g
if (strIn.substring(0, pos).replace(regEx, ‘‘) === key) {
value = strIn.substring(pos + 1, strIn.length)
}
}
return unescape(value)
}
/**********************************
* 判断某个cookie是否存在
*/
export const containCookie = function (key) {
let allcookies = document.cookie
let cookiePos = allcookies.indexOf(key)
if (cookiePos > -1) {
return true
}
return false
}
/**********************************
* 移除某个cookie
*
* 如果只移除一个,传第一个参数
* 如果全部移除,传两个参数,如(‘‘, true)
*/
export const removeCookie = function (key, removeAll) {
let removeAllVal = typeof removeAll === ‘boolean‘ ? removeAll : false
/* eslint-disable no-useless-escape */
let keys = document.cookie.match(/[^ =;]+(?=\=)/g)
if (keys) {
for (let i = 0; i < keys.length; i++) {
if (!removeAllVal) {
if (keys[i] === key) {
document.cookie = keys[i] + ‘=0;expires=‘ + new Date(0).toUTCString()
}
} else {
document.cookie = keys[i] + ‘=0;expires=‘ + new Date(0).toUTCString()
}
}
}
}
/*******************************************************************************
* 本地存储
*/
/********************************
* localStorage
*/
/************
* 是否存在localStorage
* att 需要判断的属性
* time 过期时间,默认一天
* true 存在, false 不存在
*/
export const containLocalStorage = function (attr) {
let storage = window.localStorage
if (storage.hasOwnProperty(attr)) {
return true
} else {
return false
}
}
/********************************
* localStorage
*/
/************
* 是否存在sessionStorage
* att 需要判断的属性
* time 过期时间,默认一天
* true 存在, false 不存在
*/
export const containSessionStorage = function (attr) {
let storage = window.sessionStorage
if (storage.hasOwnProperty(attr)) {
return true
} else {
return false
}
}
/**************
* 添加sessionStorage
* json 传入字面量对象格式如{name:‘夏天‘}
*/
export const setSessionStorage = function (json) {
if (!isJson(json) || !window.sessionStorage) {
return
}
let storage = window.sessionStorage
for (let item in json) {
if (json.hasOwnProperty(item)) {
storage[item] = JSON.stringify(json[item])
}
}
}
/**************
* 获取sessionStorage
* 存在,返回对应值
* 不存在,返回‘‘
*/
export const getSessionStorage = function (attr) {
let storage = sessionStorage.getItem(attr)
if (containSessionStorage(attr)) {
let json = JSON.parse(storage)
return json
} else {
return ‘‘
}
}
/*************
* 删除localStorage
*
*/
export const delSessionStorage = function (attr) {
let storage = window.sessionStorage
if (containSessionStorage(attr)) {
storage.removeItem(attr)
}
}
/**************
* 删除全部localStorage
*/
export const delAllSessionStorage = function () {
let storage = window.sessionStorage
storage.clear()
}
/**************
* 优先获取本地数据
* param 要获取的参数, 请求参数, 请求路径, 是否植入到存储
*/
export const getSessionLocalDataFirst = function (getData, postData, url, boo) {
return new Promise((resolve, reject) => {
if (getSessionStorage(getData)) {
let obj = getSessionStorage(getData)
resolve(obj)
} else {
Fecth(url, postData).then(res => {
if (res.data.code === codeState.OKCODE) {
if (boo) {
let obj = {}
obj[getData] = res.data.data
console.log(111)
setSessionStorage(obj)
}
resolve(res.data.data)
}
})
}
})
}
/**************
* 优先获取本地数据
* param 要获取的参数, 请求参数, 请求路径, 是否植入到存储
*/
export const getLocalDataFirst = function (getData, postData, url, boo) {
return new Promise((resolve, reject) => {
if (getLocalStorage(getData)) {
let obj = getLocalStorage(getData)
resolve(obj)
} else {
Fecth(url, postData).then(res => {
if (res.data.code === codeState.OKCODE) {
if (boo) {
let obj = {}
obj[getData] = res.data.data
console.log(111)
setLocalStorage(obj)
}
resolve(res.data.data)
}
})
}
})
}
/**************
* 添加localStorage
* json 传入字面量对象格式如{name:‘夏天‘}
*/
export const setLocalStorage = function (json) {
if (!isJson(json) || !window.localStorage) {
return
}
let storage = window.localStorage
for (let item in json) {
if (json.hasOwnProperty(item)) {
storage[item] = JSON.stringify(json[item])
}
}
}
/**************
* 获取localStorage
* 存在,返回对应值
* 不存在,返回‘‘
*/
export const getLocalStorage = function (attr) {
let storage = window.localStorage
if (containLocalStorage(attr)) {
let json = JSON.parse(storage[attr])
return json
} else {
return ‘‘
}
}
/*************
* 删除localStorage
*
*/
export const delLocalStorage = function (attr) {
let storage = window.localStorage
if (containLocalStorage(attr)) {
storage.removeItem(attr)
}
}
/**************
* 删除全部localStorage
*/
export const delAllLocalStorage = function () {
let storage = window.localStorage
storage.clear()
}
/**********************************************************************
* 格式校验类
*/
/*********************************
*为空
*
* true 空, false 非空
*/
export const isEmpty = function (value) {
if (value === null || value === undefined || value === ‘‘) {
return true
}
return false
}
/*********************************
*字符串格式
*
* true 是, false 不是
*/
export const isString = function (value) {
return !!value && value instanceof String
}
/*********************************
*数组格式
*
* true 是, false 不是
*/
export const isArray = function (value) {
return !!value && value instanceof Array
}
/************************************
* 验证密码格式
*
*true 格式正确 , false 格式不正确
*/
export const isPassword = function (value) {
let pattern = /^[\d_a-zA-Z]{6,18}$/
if (pattern.test(value)) {
return true
}
return false
}
/**************************************
* 手机号格式
* true 格式正确, false 格式不正确
*/
export const isPhone = function (value) {
let pattern = /^1[34578]\d{9}$/
if (pattern.test(value)) {
return true
}
return false
}
/************************************
* 是布尔值
*/
export const isBollean = function (value) {
return value === true || value === false
}
/*********************************************************************
* 小工具类
*/
export const goTo = function (str) {
if (str && typeof str === ‘string‘) {
window.location.href = str
}
}
export const getLocalHref = function () {
let str = window.location.href
if (str.indexOf(‘#/‘) > -1) {
str = str.substring(0, str.indexOf(‘#/‘))
}
return str
}
export const trimHandler = function (str) {
let reg = /^\s+|\s+$/g
return str.replace(reg, ‘‘)
}
/*********************************************************************
* 时间处理
*/
/********
* 重置时间对象到日期格式
* @param 时间对象
* 返回:2018-04-12 12:55:25
*/
export const formatDateObjToDate = function (date) {
let year = date.getFullYear()
let month = (date.getMonth() + 1).toString().length === 1 ? ‘0‘ + (date.getMonth() + 1).toString() : (date.getMonth() + 1)
let day = date.getDate().toString().length === 1 ? ‘0‘ + date.getDate() : date.getDate()
let hour = date.getHours().toString().length === 1 ? ‘0‘ + date.getHours() : date.getHours()
let min = date.getMinutes().toString().length === 1 ? ‘0‘ + date.getMinutes() : date.getMinutes()
let sec = date.getSeconds().toString().length === 1 ? ‘0‘ + date.getSeconds() : date.getSeconds()
return year + ‘-‘ + month + ‘-‘ + day + ‘ ‘ + hour + ‘:‘ + min + ‘:‘ + sec
}
/********
* 计算两个日期之间差几天
* @param date1/date2 两个日期
* 返回:2
*/
export const diffBetweenDates = function (date1, date2) {
let dateSpan
let iDays
date1 = Date.parse(date1)
date2 = Date.parse(date2)
dateSpan = date1 - date2
dateSpan = Math.abs(dateSpan)
iDays = Math.floor(dateSpan / (24 * 3600 * 1000))
return iDays
}
/********
* 判断两个时间段是否有交集
* @param dateRange1/dateRange2 [开始时间(2018-04-12), 结束时间[2018-05-16]]
* 返回:2018-04-12 12:55:25
*/
export const dateRangeIntersection = function (dateRange1, dateRange2) {
let beginTime1 = new Date(dateRange1[0]).getTime()
let endTime1 = new Date(dateRange1[1]).getTime()
let beginTime2 = new Date(dateRange2[0]).getTime()
let endTime2 = new Date(dateRange2[1]).getTime()
if ((beginTime1 >= endTime2) || (endTime1 <= beginTime2)) {
return false
}
return true
}
/**************************************
* 一层深拷贝
* true 格式正确, false 格式不正确
*/
export const copyDeepOnce = function (originObj) {
var targetObj = {}
for (var item in originObj) {
var val = originObj[item]
if (val instanceof Object) {
if (isArray(originObj[item])) {
targetObj[item] = copyArr(originObj[item])
} else {
targetObj[item] = copyObj(originObj[item])
}
} else {
targetObj[item] = originObj[item]
}
}
return targetObj
function isArray (value) {
return !!value && value instanceof Array
}
function copyArr (arrOrigin) {
var arr = []
for (var i = 0; i < arrOrigin.length; i++) {
arr.push(arrOrigin[i])
}
return arr
}
function copyObj (objOrigin) {
var obj = {}
for (var item in objOrigin) {
obj[item] = objOrigin[item]
}
return obj
}
}
/*******************
* 多层深拷贝
*/
export const copyDeep = function (origin) {
if (origin instanceof Object) {
if (isArray(origin)) {
var targetArr = []
for (var i = 0; i < origin.length; i++) {
targetArr.push(copyDeep(origin[i]))
}
return targetArr
} else {
var targetObj = {}
for (var item in origin) {
targetObj[item] = copyDeep(origin[item])
}
return targetObj
}
} else {
return origin
}
function isArray (value) {
return !!value && value instanceof Array
}
}
/************************************
* date 格式转换
*/
export const formatDate = function (date) {
let y = date.getFullYear()
let m = date.getMonth() + 1
m = m < 10 ? ‘0‘ + m : m
let d = date.getDate()
d = d < 10 ? (‘0‘ + d) : d
return y + ‘-‘ + m + ‘-‘ + d
}
/**************************************************************************************************************************
* dom 操作类
*/
export const getComputedAtt = function (dom, att) {
let value = (dom.currentStyle ? dom.currentStyle : getComputedStyle(dom))[att]
return value
}
/************************************
* 数组多语言保存前的数据处理
*/
export const dataProcessingHandle = function (param) {
// 将object类型转为数组类型
let arrCopy = Object.keys(param).map(key => param[key])
param = []
arrCopy.forEach((item, index) => {
if (item.LANG_ID !== ‘‘ && item.NAME !== ‘‘) {
param.push(item)
}
})
}
/*************************************************
判断开发模式
***********************/
export const devMode = function () {
let href = window.location.href
let devType = ‘official‘
if (href.indexOf(‘sim‘) > -1) { // 模拟
devType = ‘sim‘
}
if (href.indexOf(‘test‘) > -1) { // 测试
devType = ‘test‘
}
if ((href.indexOf(‘kaifa‘) > -1) || (href.indexOf(‘http://localhost:8088‘) > -1)) { // 开发
devType = ‘dev‘
}
return devType
}
以上是关于常用的工具方法的封装的主要内容,如果未能解决你的问题,请参考以下文章