index.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /**
  2. * Created by jiachenpan on 16/11/18.
  3. */
  4. /**
  5. * 构造树型结构数据
  6. * @param {*} data 数据源
  7. * @param {*} id id字段 默认 'id'
  8. * @param {*} parentId 父节点字段 默认 'parentId'
  9. * @param {*} children 孩子节点字段 默认 'children'
  10. */
  11. export function handleTree(data, id, parentId, children) {
  12. let config = {
  13. id: id || 'id',
  14. parentId: parentId || 'parentId',
  15. childrenList: children || 'children'
  16. };
  17. var childrenListMap = {};
  18. var nodeIds = {};
  19. var tree = [];
  20. for (let d of data) {
  21. let parentId = d[config.parentId];
  22. if (childrenListMap[parentId] == null) {
  23. childrenListMap[parentId] = [];
  24. }
  25. nodeIds[d[config.id]] = d;
  26. childrenListMap[parentId].push(d);
  27. }
  28. for (let d of data) {
  29. let parentId = d[config.parentId];
  30. if (nodeIds[parentId] == null) {
  31. tree.push(d);
  32. }
  33. }
  34. for (let t of tree) {
  35. adaptToChildrenList(t);
  36. }
  37. function adaptToChildrenList(o) {
  38. if (childrenListMap[o[config.id]] !== null) {
  39. o[config.childrenList] = childrenListMap[o[config.id]];
  40. }
  41. if (o[config.childrenList]) {
  42. for (let c of o[config.childrenList]) {
  43. adaptToChildrenList(c);
  44. }
  45. }
  46. }
  47. return tree;
  48. }
  49. // 表单重置
  50. export function resetForm(refName) {
  51. if (this.$refs[refName]) {
  52. this.$refs[refName].resetFields();
  53. }
  54. }
  55. export function parseTime(time, cFormat) {
  56. if (arguments.length === 0) {
  57. return null
  58. }
  59. const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  60. let date
  61. if (typeof time === 'object') {
  62. date = time
  63. } else {
  64. if (('' + time).length === 10) time = parseInt(time) * 1000
  65. date = new Date(time)
  66. }
  67. const formatObj = {
  68. y: date.getFullYear(),
  69. m: date.getMonth() + 1,
  70. d: date.getDate(),
  71. h: date.getHours(),
  72. i: date.getMinutes(),
  73. s: date.getSeconds(),
  74. a: date.getDay()
  75. }
  76. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
  77. let value = formatObj[key]
  78. if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
  79. if (result.length > 0 && value < 10) {
  80. value = '0' + value
  81. }
  82. return value || 0
  83. })
  84. return time_str
  85. }
  86. export function formatTime(time, option) {
  87. time = +time * 1000
  88. const d = new Date(time)
  89. const now = Date.now()
  90. const diff = (now - d) / 1000
  91. if (diff < 30) {
  92. return '刚刚'
  93. } else if (diff < 3600) { // less 1 hour
  94. return Math.ceil(diff / 60) + '分钟前'
  95. } else if (diff < 3600 * 24) {
  96. return Math.ceil(diff / 3600) + '小时前'
  97. } else if (diff < 3600 * 24 * 2) {
  98. return '1天前'
  99. }
  100. if (option) {
  101. return parseTime(time, option)
  102. } else {
  103. return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  104. }
  105. }
  106. // 格式化时间
  107. export function getQueryObject(url) {
  108. url = url == null ? window.location.href : url
  109. const search = url.substring(url.lastIndexOf('?') + 1)
  110. const obj = {}
  111. const reg = /([^?&=]+)=([^?&=]*)/g
  112. search.replace(reg, (rs, $1, $2) => {
  113. const name = decodeURIComponent($1)
  114. let val = decodeURIComponent($2)
  115. val = String(val)
  116. obj[name] = val
  117. return rs
  118. })
  119. return obj
  120. }
  121. /**
  122. *get getByteLen
  123. * @param {Sting} val input value
  124. * @returns {number} output value
  125. */
  126. export function getByteLen(val) {
  127. let len = 0
  128. for (let i = 0; i < val.length; i++) {
  129. if (val[i].match(/[^\x00-\xff]/ig) != null) {
  130. len += 1
  131. } else { len += 0.5 }
  132. }
  133. return Math.floor(len)
  134. }
  135. export function cleanArray(actual) {
  136. const newArray = []
  137. for (let i = 0; i < actual.length; i++) {
  138. if (actual[i]) {
  139. newArray.push(actual[i])
  140. }
  141. }
  142. return newArray
  143. }
  144. export function param(json) {
  145. if (!json) return ''
  146. return cleanArray(Object.keys(json).map(key => {
  147. if (json[key] === undefined) return ''
  148. return encodeURIComponent(key) + '=' +
  149. encodeURIComponent(json[key])
  150. })).join('&')
  151. }
  152. export function param2Obj(url) {
  153. const search = url.split('?')[1]
  154. if (!search) {
  155. return {}
  156. }
  157. return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
  158. }
  159. export function html2Text(val) {
  160. const div = document.createElement('div')
  161. div.innerHTML = val
  162. return div.textContent || div.innerText
  163. }
  164. export function objectMerge(target, source) {
  165. /* Merges two objects,
  166. giving the last one precedence */
  167. if (typeof target !== 'object') {
  168. target = {}
  169. }
  170. if (Array.isArray(source)) {
  171. return source.slice()
  172. }
  173. for (const property in source) {
  174. if (source.hasOwnProperty(property)) {
  175. const sourceProperty = source[property]
  176. if (typeof sourceProperty === 'object') {
  177. target[property] = objectMerge(target[property], sourceProperty)
  178. continue
  179. }
  180. target[property] = sourceProperty
  181. }
  182. }
  183. return target
  184. }
  185. export function scrollTo(element, to, duration) {
  186. if (duration <= 0) return
  187. const difference = to - element.scrollTop
  188. const perTick = difference / duration * 10
  189. setTimeout(() => {
  190. console.log(new Date())
  191. element.scrollTop = element.scrollTop + perTick
  192. if (element.scrollTop === to) return
  193. scrollTo(element, to, duration - 10)
  194. }, 10)
  195. }
  196. export function toggleClass(element, className) {
  197. if (!element || !className) {
  198. return
  199. }
  200. let classString = element.className
  201. const nameIndex = classString.indexOf(className)
  202. if (nameIndex === -1) {
  203. classString += '' + className
  204. } else {
  205. classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length)
  206. }
  207. element.className = classString
  208. }
  209. export const pickerOptions = [
  210. {
  211. text: '今天',
  212. onClick(picker) {
  213. const end = new Date()
  214. const start = new Date(new Date().toDateString())
  215. end.setTime(start.getTime())
  216. picker.$emit('pick', [start, end])
  217. }
  218. }, {
  219. text: '最近一周',
  220. onClick(picker) {
  221. const end = new Date(new Date().toDateString())
  222. const start = new Date()
  223. start.setTime(end.getTime() - 3600 * 1000 * 24 * 7)
  224. picker.$emit('pick', [start, end])
  225. }
  226. }, {
  227. text: '最近一个月',
  228. onClick(picker) {
  229. const end = new Date(new Date().toDateString())
  230. const start = new Date()
  231. start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
  232. picker.$emit('pick', [start, end])
  233. }
  234. }, {
  235. text: '最近三个月',
  236. onClick(picker) {
  237. const end = new Date(new Date().toDateString())
  238. const start = new Date()
  239. start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
  240. picker.$emit('pick', [start, end])
  241. }
  242. }]
  243. export function getTime(type) {
  244. if (type === 'start') {
  245. return new Date().getTime() - 3600 * 1000 * 24 * 90
  246. } else {
  247. return new Date(new Date().toDateString())
  248. }
  249. }
  250. export function debounce(func, wait, immediate) {
  251. let timeout, args, context, timestamp, result
  252. const later = function() {
  253. // 据上一次触发时间间隔
  254. const last = +new Date() - timestamp
  255. // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
  256. if (last < wait && last > 0) {
  257. timeout = setTimeout(later, wait - last)
  258. } else {
  259. timeout = null
  260. // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  261. if (!immediate) {
  262. result = func.apply(context, args)
  263. if (!timeout) context = args = null
  264. }
  265. }
  266. }
  267. return function(...args) {
  268. context = this
  269. timestamp = +new Date()
  270. const callNow = immediate && !timeout
  271. // 如果延时不存在,重新设定延时
  272. if (!timeout) timeout = setTimeout(later, wait)
  273. if (callNow) {
  274. result = func.apply(context, args)
  275. context = args = null
  276. }
  277. return result
  278. }
  279. }
  280. export function deepClone(source) {
  281. if (!source && typeof source !== 'object') {
  282. throw new Error('error arguments', 'shallowClone')
  283. }
  284. const targetObj = source.constructor === Array ? [] : {}
  285. for (const keys in source) {
  286. if (source.hasOwnProperty(keys)) {
  287. if (source[keys] && typeof source[keys] === 'object') {
  288. targetObj[keys] = source[keys].constructor === Array ? [] : {}
  289. targetObj[keys] = deepClone(source[keys])
  290. } else {
  291. targetObj[keys] = source[keys]
  292. }
  293. }
  294. }
  295. return targetObj
  296. }