common.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. if (!String.prototype.endsWith) {
  2. //判断String这个对象原型是否有endsWith方法,没有的话,就用加上这个方法
  3. Object.defineProperty(String.prototype, 'endsWith', {
  4. enumerable: false,
  5. configurable: false,
  6. writable: false,
  7. value: function (searchString, position) {
  8. position = position || this.length;
  9. position = position - searchString.length;
  10. var lastIndex = this.lastIndexOf(searchString);
  11. return lastIndex !== -1 && lastIndex === position;
  12. }
  13. });
  14. }
  15. /**
  16. * 浏览器跳转链接
  17. * @param {{r: string, id}} params
  18. * @param {bool} newWindow
  19. */
  20. const navigateTo = (params, newWindow = false) => {
  21. let url = null;
  22. if (typeof params === 'string') {
  23. url = params;
  24. } else {
  25. const queryString = Qs.stringify(params);
  26. url = `${_scriptUrl}?${queryString}`;
  27. }
  28. if (newWindow) {
  29. window.open(url);
  30. } else {
  31. window.location.href = url;
  32. }
  33. };
  34. const historyGo = (number) => {
  35. if (typeof number === 'number') {
  36. window.history.go(number);
  37. }
  38. };
  39. const Navigate = {
  40. install(Vue, options) {
  41. Vue.prototype.$navigate = function (params, newWindow) {
  42. navigateTo(params, newWindow);
  43. }
  44. }
  45. };
  46. const HistoryGo = {
  47. install(Vue, options) {
  48. Vue.prototype.$historyGo = function (number) {
  49. historyGo(number);
  50. }
  51. }
  52. };
  53. Vue.use(Navigate);
  54. Vue.use(HistoryGo);
  55. /**
  56. * 获取get请求参数的值
  57. * @param {String} name
  58. * @returns {String||null}
  59. */
  60. const getQuery = (name) => {
  61. const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  62. const r = window.location.search.substr(1).match(reg);
  63. if (r != null) {
  64. return decodeURIComponent(r[2]);
  65. }
  66. return null;
  67. };
  68. const getLastMonth = () =>{
  69. const currentDate = new Date();
  70. const lastMonthStartDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1);
  71. const lastMonthEndDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0);
  72. return [lastMonthStartDate, lastMonthEndDate]
  73. };
  74. /**
  75. * 获取cookie值
  76. * @param {String} cname
  77. * @returns {String||null}
  78. */
  79. const getCookieValue = (cname) => {
  80. var name = cname + "=";
  81. var decodedCookie = decodeURIComponent(document.cookie);
  82. var ca = decodedCookie.split(';');
  83. for (var i = 0; i < ca.length; i++) {
  84. var c = ca[i];
  85. while (c.charAt(0) == ' ') {
  86. c = c.substring(1);
  87. }
  88. if (c.indexOf(name) == 0) {
  89. return c.substring(name.length, c.length);
  90. }
  91. }
  92. return "";
  93. }
  94. /**
  95. * 生成随机字符串
  96. * @param {Number} len
  97. * @returns {string}
  98. */
  99. const randomString = (len) => {
  100. len = len || 32;
  101. let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  102. /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  103. let maxPos = $chars.length;
  104. let pwd = '';
  105. for (i = 0; i < len; i++) {
  106. pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  107. }
  108. return pwd;
  109. };
  110. const common = axios.create({
  111. transformRequest: [function (data, headers) {
  112. if (data instanceof FormData) {
  113. data.append('_csrf', _csrf);
  114. } else {
  115. if (data && !data['_csrf']) {
  116. data['_csrf'] = _csrf;
  117. }
  118. data = Qs.stringify(data);
  119. }
  120. return data;
  121. }],
  122. });
  123. window.request = common;
  124. common.defaults.baseURL = _scriptUrl;
  125. common.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  126. common.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
  127. common.interceptors.request.use(function (config) {
  128. return config;
  129. }, function (error) {
  130. return Promise.reject(error);
  131. });
  132. common.interceptors.response.use(function (response) {
  133. if (response.data && typeof response.data.code !== 'undefined') {
  134. if (response.data.code >= 400) {
  135. if (_layout) {
  136. _layout.$alert(response.data.msg, '错误');
  137. } else {
  138. console.log(response.data);
  139. }
  140. } else {
  141. return response;
  142. }
  143. } else {
  144. return Promise.reject(response);
  145. }
  146. }, function (error) {
  147. if (_layout) {
  148. console.log(error);
  149. } else {
  150. console.log(error);
  151. }
  152. return Promise.reject(error);
  153. });
  154. Vue.use({
  155. install(Vue, options) {
  156. Vue.prototype.$request = request;
  157. }
  158. });
  159. // 传入请求地址与页数获取列表
  160. const loadList = (url, page) => {
  161. return request({
  162. params: {
  163. r: url,
  164. page: page
  165. },
  166. }).then(e => {
  167. if (e.data.code === 0) {
  168. return e.data.data;
  169. } else {
  170. this.$message.error(e.data.msg);
  171. }
  172. }).catch(e => {
  173. });
  174. };
  175. /**
  176. * 判断一个值是否为空
  177. * @param {*} val
  178. */
  179. const isEmpty = (val) => {
  180. // null or undefined
  181. if (val == null) return true;
  182. if (typeof val === 'boolean') return false;
  183. if (typeof val === 'number') return !val;
  184. if (val instanceof Error) return val.message === '';
  185. switch (Object.prototype.toString.call(val)) {
  186. // String or Array
  187. case '[object String]':
  188. case '[object Array]':
  189. return !val.length;
  190. // Map or Set or File
  191. case '[object File]':
  192. case '[object Map]':
  193. case '[object Set]': {
  194. return !val.size;
  195. }
  196. // Plain Object
  197. case '[object Object]': {
  198. return !Object.keys(val).length;
  199. }
  200. }
  201. return false;
  202. }
  203. /**
  204. * 判断一个元素是否在数组中
  205. * @param {*} search 查找的元素
  206. * @param {*} array 数组
  207. */
  208. const inArray = (search, array) => {
  209. for (var i in array) {
  210. if (array[i] == search) return true;
  211. }
  212. return false;
  213. }
  214. /**
  215. * 时间格式化
  216. * @param {*} fmt YYYY-mm-dd HH:MM:SS
  217. * @param {*} date 日期
  218. */
  219. const dateFormat = (fmt, date) => {
  220. let ret;
  221. const opt = {
  222. "Y+": date.getFullYear().toString(), // 年
  223. "m+": (date.getMonth() + 1).toString(), // 月
  224. "d+": date.getDate().toString(), // 日
  225. "H+": date.getHours().toString(), // 时
  226. "M+": date.getMinutes().toString(), // 分
  227. "S+": date.getSeconds().toString() // 秒
  228. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  229. };
  230. for (let k in opt) {
  231. ret = new RegExp("(" + k + ")").exec(fmt);
  232. if (ret) {
  233. fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
  234. };
  235. };
  236. return fmt;
  237. }
  238. /**
  239. * 转成N位小数,并格式化显示
  240. * @param {*} num 数字
  241. * @param {*} place 小数保留位数
  242. * @param {*} is_negative 是否允许负数
  243. */
  244. const toNumber = (num,place = 0,is_negative = false)=>{
  245. var t = num.charAt(0);
  246. let pattern = new RegExp('^\\D*(\\d*(?:\\.\\d{0,'+place+'})?).*$','g');
  247. num = num.replace(".", "$#$") //把第一个字符'.'替换成'$#$'
  248. .replace(/\./g, "") //把其余的字符'.'替换为空
  249. .replace("$#$", ".") //把字符'$#$'替换回原来的'.'
  250. .replace(/[^\d.]/g, "") //只能输入数字和'.'
  251. .replace(/^\./g, "") //不能以'.'开头
  252. .replace(pattern, '$1') //只保留2位小数  
  253. if (t == '-' && is_negative === true) {
  254. num = '-' + num
  255. }
  256. if(num.split('.').length == 1 && num.startsWith(0) && num.length > 1) num = 0;// 0开头的输入值改为0
  257. return num
  258. }
  259. const getObjects = (obj, key, val)=> {
  260. var objects = [];
  261. for (var i in obj) {
  262. if (!obj.hasOwnProperty(i)) continue;
  263. if (typeof obj[i] == 'object') {
  264. objects = objects.concat(getObjects(obj[i], key, val));
  265. } else
  266. //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)
  267. if (i == key && obj[i] == val || i == key && val == '') { //
  268. objects.push(obj);
  269. } else if (obj[i] == val && key == ''){
  270. //only add if the object is not already in the array
  271. if (objects.lastIndexOf(obj) == -1){
  272. objects.push(obj);
  273. }
  274. }
  275. }
  276. return objects;
  277. }
  278. /**
  279. * 获取对象中包含指定key的值列表
  280. * @param {*} obj
  281. * @param {*} key
  282. */
  283. const getValues = (obj, key) => {
  284. var objects = [];
  285. for (var i in obj) {
  286. if (!obj.hasOwnProperty(i)) continue;
  287. if (typeof obj[i] == 'object') {
  288. objects = objects.concat(getValues(obj[i], key));
  289. } else if (i == key) {
  290. objects.push(obj[i]);
  291. }
  292. }
  293. return objects;
  294. }
  295. /**
  296. * 获取对象中包含指定值的key列表
  297. * @param {*} obj
  298. * @param {*} val
  299. */
  300. const getKeys = (obj, val) => {
  301. var objects = [];
  302. for (var i in obj) {
  303. if (!obj.hasOwnProperty(i)) continue;
  304. if (typeof obj[i] == 'object') {
  305. objects = objects.concat(getKeys(obj[i], val));
  306. } else if (obj[i] == val) {
  307. objects.push(i);
  308. }
  309. }
  310. return objects;
  311. }
  312. /**
  313. * 获取对象的key列表
  314. * @param {*} obj
  315. */
  316. const objectKeys = (obj) => {
  317. var keys = [];
  318. for (var i in obj) {
  319. keys.push(i);
  320. }
  321. return keys;
  322. }
  323. /**
  324. * 判断是否为JOSN字符串
  325. */
  326. function isJSON(str) {
  327. if (typeof str == 'string') {
  328. try {
  329. var obj=JSON.parse(str);
  330. if(typeof obj == 'object' && obj ){
  331. return true;
  332. }else{
  333. return false;
  334. }
  335. } catch(e) {
  336. console.log('error:'+str+'!!!'+e);
  337. return false;
  338. }
  339. }
  340. console.log('It is not a string!')
  341. }