index.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. //解析日期
  2. export function parseTime(time, cFormat) {
  3. if (arguments.length === 0) {
  4. return null
  5. }
  6. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
  7. let date;
  8. if (typeof time === 'object') {
  9. date = time
  10. } else {
  11. if (('' + time).length === 10) time = parseInt(time) * 1000;
  12. date = new Date(time)
  13. }
  14. const formatObj = {
  15. y: date.getFullYear(),
  16. m: date.getMonth() + 1,
  17. d: date.getDate(),
  18. h: date.getHours(),
  19. i: date.getMinutes(),
  20. s: date.getSeconds(),
  21. a: date.getDay()
  22. };
  23. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  24. let value = formatObj[key];
  25. // Note: getDay() returns 0 on Sunday
  26. if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
  27. if (result.length > 0 && value < 10) {
  28. value = '0' + value
  29. }
  30. return value || 0
  31. });
  32. return time_str
  33. }
  34. //格式化日期
  35. export function formatTime(time, option) {
  36. time = +time * 1000;
  37. const d = new Date(time);
  38. const now = Date.now();
  39. const diff = (now - d) / 1000;
  40. if (diff < 30) {
  41. return '刚刚'
  42. } else if (diff < 3600) {
  43. // less 1 hour
  44. return Math.ceil(diff / 60) + '分钟前'
  45. } else if (diff < 3600 * 24) {
  46. return Math.ceil(diff / 3600) + '小时前'
  47. } else if (diff < 3600 * 24 * 2) {
  48. return '1天前'
  49. }
  50. if (option) {
  51. return parseTime(time, option)
  52. } else {
  53. return (
  54. d.getMonth() +
  55. 1 +
  56. '月' +
  57. d.getDate() +
  58. '日' +
  59. d.getHours() +
  60. '时' +
  61. d.getMinutes() +
  62. '分'
  63. )
  64. }
  65. }
  66. export function formatMillisecondTime(time) {
  67. const d = new Date(time);
  68. return parseTime(d)
  69. }
  70. //获取参数时间
  71. export function getQueryObject(url) {
  72. url = url == null ? window.location.href : url;
  73. const search = url.substring(url.lastIndexOf('?') + 1);
  74. const obj = {};
  75. const reg = /([^?&=]+)=([^?&=]*)/g;
  76. search.replace(reg, (rs, $1, $2) => {
  77. const name = decodeURIComponent($1);
  78. let val = decodeURIComponent($2);
  79. val = String(val);
  80. obj[name] = val;
  81. return rs
  82. });
  83. return obj
  84. }
  85. /**
  86. *get getByteLen
  87. * @param {Sting} val input value
  88. * @returns {number} output value
  89. */
  90. export function getByteLen(val) {
  91. let len = 0;
  92. for (let i = 0; i < val.length; i++) {
  93. if (val[i].match(/[^\x00-\xff]/gi) != null) {
  94. len += 1
  95. } else {
  96. len += 0.5
  97. }
  98. }
  99. return Math.floor(len)
  100. }
  101. export function cleanArray(actual) {
  102. const newArray = [];
  103. for (let i = 0; i < actual.length; i++) {
  104. if (actual[i]) {
  105. newArray.push(actual[i])
  106. }
  107. }
  108. return newArray
  109. }
  110. export function param(json) {
  111. if (!json) return '';
  112. return cleanArray(
  113. Object.keys(json).map(key => {
  114. if (json[key] === undefined) return '';
  115. return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
  116. })
  117. ).join('&')
  118. }
  119. export function param2Obj(url) {
  120. const search = url.split('?')[1];
  121. if (!search) {
  122. return {}
  123. }
  124. return JSON.parse(
  125. '{"' +
  126. decodeURIComponent(search)
  127. .replace(/"/g, '\\"')
  128. .replace(/&/g, '","')
  129. .replace(/=/g, '":"') +
  130. '"}'
  131. )
  132. }
  133. export function html2Text(val) {
  134. const div = document.createElement('div');
  135. div.innerHTML = val;
  136. return div.textContent || div.innerText
  137. }
  138. export function objectMerge(target, source) {
  139. /* Merges two objects,
  140. giving the last one precedence */
  141. if (typeof target !== 'object') {
  142. target = {}
  143. }
  144. if (Array.isArray(source)) {
  145. return source.slice()
  146. }
  147. Object.keys(source).forEach(property => {
  148. const sourceProperty = source[property];
  149. if (typeof sourceProperty === 'object') {
  150. target[property] = objectMerge(target[property], sourceProperty)
  151. } else {
  152. target[property] = sourceProperty
  153. }
  154. });
  155. return target
  156. }
  157. export function scrollTo(element, to, duration) {
  158. if (duration <= 0) return;
  159. const difference = to - element.scrollTop;
  160. const perTick = (difference / duration) * 10;
  161. setTimeout(() => {
  162. element.scrollTop = element.scrollTop + perTick;
  163. if (element.scrollTop === to) return;
  164. scrollTo(element, to, duration - 10)
  165. }, 10)
  166. }
  167. export function toggleClass(element, className) {
  168. if (!element || !className) {
  169. return
  170. }
  171. let classString = element.className;
  172. const nameIndex = classString.indexOf(className);
  173. if (nameIndex === -1) {
  174. classString += '' + className
  175. } else {
  176. classString =
  177. classString.substr(0, nameIndex) +
  178. classString.substr(nameIndex + className.length)
  179. }
  180. element.className = classString
  181. }
  182. export const pickerOptions = [
  183. {
  184. text: '今天',
  185. onClick(picker) {
  186. const end = new Date();
  187. const start = new Date(new Date().toDateString());
  188. end.setTime(start.getTime());
  189. picker.$emit('pick', [start, end])
  190. }
  191. },
  192. {
  193. text: '最近一周',
  194. onClick(picker) {
  195. const end = new Date(new Date().toDateString());
  196. const start = new Date();
  197. start.setTime(end.getTime() - 3600 * 1000 * 24 * 7);
  198. picker.$emit('pick', [start, end])
  199. }
  200. },
  201. {
  202. text: '最近一个月',
  203. onClick(picker) {
  204. const end = new Date(new Date().toDateString());
  205. const start = new Date();
  206. start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
  207. picker.$emit('pick', [start, end])
  208. }
  209. },
  210. {
  211. text: '最近三个月',
  212. onClick(picker) {
  213. const end = new Date(new Date().toDateString());
  214. const start = new Date();
  215. start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
  216. picker.$emit('pick', [start, end])
  217. }
  218. }
  219. ];
  220. export function getTime(type) {
  221. if (type === 'start') {
  222. return new Date().getTime() - 3600 * 1000 * 24 * 90
  223. } else {
  224. return new Date(new Date().toDateString())
  225. }
  226. }
  227. export function debounce(func, wait, immediate) {
  228. let timeout, args, context, timestamp, result;
  229. const later = function () {
  230. // 据上一次触发时间间隔
  231. const last = +new Date() - timestamp;
  232. // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
  233. if (last < wait && last > 0) {
  234. timeout = setTimeout(later, wait - last)
  235. } else {
  236. timeout = null;
  237. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  238. if (!immediate) {
  239. result = func.apply(context, args);
  240. if (!timeout) context = args = null
  241. }
  242. }
  243. };
  244. return function (...args) {
  245. context = this;
  246. timestamp = +new Date();
  247. const callNow = immediate && !timeout;
  248. // 如果延时不存在,重新设定延时
  249. if (!timeout) timeout = setTimeout(later, wait);
  250. if (callNow) {
  251. result = func.apply(context, args);
  252. context = args = null
  253. }
  254. return result
  255. }
  256. }
  257. /**
  258. * This is just a simple version of deep copy
  259. * Has a lot of edge cases bug
  260. * If you want to use a perfect deep copy, use lodash's _.cloneDeep
  261. */
  262. export function deepClone(source) {
  263. if (!source && typeof source !== 'object') {
  264. throw new Error('error arguments', 'shallowClone')
  265. }
  266. const targetObj = source.constructor === Array ? [] : {};
  267. Object.keys(source).forEach(keys => {
  268. if (source[keys] && typeof source[keys] === 'object') {
  269. targetObj[keys] = deepClone(source[keys])
  270. } else {
  271. targetObj[keys] = source[keys]
  272. }
  273. });
  274. return targetObj
  275. }
  276. export function uniqueArr(arr) {
  277. return Array.from(new Set(arr))
  278. }
  279. export function randomString(len) {
  280. const strlen = len || 32;
  281. var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  282. var maxPos = $chars.length;
  283. var pwd = '';
  284. for (let i = 0; i < strlen; i++) {
  285. pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  286. }
  287. return pwd
  288. }
  289. //排序
  290. export function sortKey(array, key) {
  291. return array.sort(function (a, b) {
  292. var x = a[key];
  293. var y = b[key];
  294. return ((x < y) ? -1 : (x > y) ? 1 : 0)
  295. });
  296. }
  297. /**
  298. * 根据key和options匹配对应的value
  299. * @param {String|Number} key 需要匹配的键值
  300. * @param {Array} options 选项数组,格式为 [{value: 1, label: '选项1'}, ...]
  301. * @param {String} valueKey 选项值的键名,默认为 'value'
  302. * @param {String} labelKey 选项标签的键名,默认为 'label'
  303. * @returns {String|undefined} 匹配到的标签值
  304. */
  305. export function getValueByKey(key, options = [], valueKey = 'value', labelKey = 'label') {
  306. if (key === undefined || key === null || !options.length) return '';
  307. const target = options.find(item => item[valueKey] === key);
  308. return target ? target[labelKey] : '';
  309. }