if (!String.prototype.endsWith) { //判断String这个对象原型是否有endsWith方法,没有的话,就用加上这个方法 Object.defineProperty(String.prototype, 'endsWith', { enumerable: false, configurable: false, writable: false, value: function (searchString, position) { position = position || this.length; position = position - searchString.length; var lastIndex = this.lastIndexOf(searchString); return lastIndex !== -1 && lastIndex === position; } }); } /** * 浏览器跳转链接 * @param {{r: string, id}} params * @param {bool} newWindow */ const navigateTo = (params, newWindow = false) => { let url = null; if (typeof params === 'string') { url = params; } else { const queryString = Qs.stringify(params); url = `${_scriptUrl}?${queryString}`; } if (newWindow) { window.open(url); } else { window.location.href = url; } }; const historyGo = (number) => { if (typeof number === 'number') { window.history.go(number); } }; const Navigate = { install(Vue, options) { Vue.prototype.$navigate = function (params, newWindow) { navigateTo(params, newWindow); } } }; const HistoryGo = { install(Vue, options) { Vue.prototype.$historyGo = function (number) { historyGo(number); } } }; Vue.use(Navigate); Vue.use(HistoryGo); /** * 获取get请求参数的值 * @param {String} name * @returns {String||null} */ const getQuery = (name) => { const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); const r = window.location.search.substr(1).match(reg); if (r != null) { return decodeURIComponent(r[2]); } return null; }; const getLastMonth = () =>{ const currentDate = new Date(); const lastMonthStartDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1); const lastMonthEndDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0); return [lastMonthStartDate, lastMonthEndDate] }; /** * 获取cookie值 * @param {String} cname * @returns {String||null} */ const getCookieValue = (cname) => { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } /** * 生成随机字符串 * @param {Number} len * @returns {string} */ const randomString = (len) => { len = len || 32; let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/ let maxPos = $chars.length; let pwd = ''; for (i = 0; i < len; i++) { pwd += $chars.charAt(Math.floor(Math.random() * maxPos)); } return pwd; }; const common = axios.create({ transformRequest: [function (data, headers) { if (data instanceof FormData) { data.append('_csrf', _csrf); } else { if (data && !data['_csrf']) { data['_csrf'] = _csrf; } data = Qs.stringify(data); } return data; }], }); window.request = common; common.defaults.baseURL = _scriptUrl; common.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; common.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; common.interceptors.request.use(function (config) { return config; }, function (error) { return Promise.reject(error); }); common.interceptors.response.use(function (response) { if (response.data && typeof response.data.code !== 'undefined') { if (response.data.code >= 400) { if (_layout) { _layout.$alert(response.data.msg, '错误'); } else { console.log(response.data); } } else { return response; } } else { return Promise.reject(response); } }, function (error) { if (_layout) { console.log(error); } else { console.log(error); } return Promise.reject(error); }); Vue.use({ install(Vue, options) { Vue.prototype.$request = request; } }); // 传入请求地址与页数获取列表 const loadList = (url, page) => { return request({ params: { r: url, page: page }, }).then(e => { if (e.data.code === 0) { return e.data.data; } else { this.$message.error(e.data.msg); } }).catch(e => { }); }; /** * 判断一个值是否为空 * @param {*} val */ const isEmpty = (val) => { // null or undefined if (val == null) return true; if (typeof val === 'boolean') return false; if (typeof val === 'number') return !val; if (val instanceof Error) return val.message === ''; switch (Object.prototype.toString.call(val)) { // String or Array case '[object String]': case '[object Array]': return !val.length; // Map or Set or File case '[object File]': case '[object Map]': case '[object Set]': { return !val.size; } // Plain Object case '[object Object]': { return !Object.keys(val).length; } } return false; } /** * 判断一个元素是否在数组中 * @param {*} search 查找的元素 * @param {*} array 数组 */ const inArray = (search, array) => { for (var i in array) { if (array[i] == search) return true; } return false; } /** * 时间格式化 * @param {*} fmt YYYY-mm-dd HH:MM:SS * @param {*} date 日期 */ const dateFormat = (fmt, date) => { let ret; const opt = { "Y+": date.getFullYear().toString(), // 年 "m+": (date.getMonth() + 1).toString(), // 月 "d+": date.getDate().toString(), // 日 "H+": date.getHours().toString(), // 时 "M+": date.getMinutes().toString(), // 分 "S+": date.getSeconds().toString() // 秒 // 有其他格式化字符需求可以继续添加,必须转化成字符串 }; for (let k in opt) { ret = new RegExp("(" + k + ")").exec(fmt); if (ret) { fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0"))) }; }; return fmt; } /** * 转成N位小数,并格式化显示 * @param {*} num 数字 * @param {*} place 小数保留位数 * @param {*} is_negative 是否允许负数 */ const toNumber = (num,place = 0,is_negative = false)=>{ var t = num.charAt(0); let pattern = new RegExp('^\\D*(\\d*(?:\\.\\d{0,'+place+'})?).*$','g'); num = num.replace(".", "$#$") //把第一个字符'.'替换成'$#$' .replace(/\./g, "") //把其余的字符'.'替换为空 .replace("$#$", ".") //把字符'$#$'替换回原来的'.' .replace(/[^\d.]/g, "") //只能输入数字和'.' .replace(/^\./g, "") //不能以'.'开头 .replace(pattern, '$1') //只保留2位小数   if (t == '-' && is_negative === true) { num = '-' + num } if(num.split('.').length == 1 && num.startsWith(0) && num.length > 1) num = 0;// 0开头的输入值改为0 return num } const getObjects = (obj, key, val)=> { var objects = []; for (var i in obj) { if (!obj.hasOwnProperty(i)) continue; if (typeof obj[i] == 'object') { objects = objects.concat(getObjects(obj[i], key, val)); } else //if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not) if (i == key && obj[i] == val || i == key && val == '') { // objects.push(obj); } else if (obj[i] == val && key == ''){ //only add if the object is not already in the array if (objects.lastIndexOf(obj) == -1){ objects.push(obj); } } } return objects; } /** * 获取对象中包含指定key的值列表 * @param {*} obj * @param {*} key */ const getValues = (obj, key) => { var objects = []; for (var i in obj) { if (!obj.hasOwnProperty(i)) continue; if (typeof obj[i] == 'object') { objects = objects.concat(getValues(obj[i], key)); } else if (i == key) { objects.push(obj[i]); } } return objects; } /** * 获取对象中包含指定值的key列表 * @param {*} obj * @param {*} val */ const getKeys = (obj, val) => { var objects = []; for (var i in obj) { if (!obj.hasOwnProperty(i)) continue; if (typeof obj[i] == 'object') { objects = objects.concat(getKeys(obj[i], val)); } else if (obj[i] == val) { objects.push(i); } } return objects; } /** * 获取对象的key列表 * @param {*} obj */ const objectKeys = (obj) => { var keys = []; for (var i in obj) { keys.push(i); } return keys; } /** * 判断是否为JOSN字符串 */ function isJSON(str) { if (typeof str == 'string') { try { var obj=JSON.parse(str); if(typeof obj == 'object' && obj ){ return true; }else{ return false; } } catch(e) { console.log('error:'+str+'!!!'+e); return false; } } console.log('It is not a string!') }