index.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import Vue from 'vue'
  2. import router from '@/router'
  3. import store from '@/store'
  4. import $http from './httpRequest'
  5. /**
  6. * 是否有权限
  7. * @param {*} key
  8. */
  9. export function hasPermission (key) {
  10. return JSON.parse(localStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
  11. }
  12. /**
  13. * 树形数据转换
  14. * @param {*} data list数据
  15. * @param {*} id 主键ID
  16. * @param {*} pid 上级ID
  17. * @param childrenKey 子list数据的key
  18. */
  19. export function treeDataTranslate (data, id = 'id', pid = 'parentId', childrenKey = 'children') {
  20. let res = []
  21. let temp = {}
  22. for (let i = 0; i < data.length; i++) {
  23. temp[data[i][id]] = data[i]
  24. }
  25. for (let k = 0; k < data.length; k++) {
  26. if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
  27. if (!temp[data[k][pid]][childrenKey]) {
  28. temp[data[k][pid]][childrenKey] = []
  29. }
  30. if (!temp[data[k][pid]]['_level']) {
  31. temp[data[k][pid]]['_level'] = 1
  32. }
  33. data[k]['_level'] = temp[data[k][pid]]._level + 1
  34. temp[data[k][pid]][childrenKey].push(data[k])
  35. } else {
  36. res.push(data[k])
  37. }
  38. }
  39. return res
  40. }
  41. /**
  42. * 清除登录信息
  43. */
  44. export function clearLoginInfo () {
  45. Vue.cookie.delete('token')
  46. store.commit('resetStore')
  47. localStorage.removeItem('allMenuList')
  48. localStorage.removeItem('permissions')
  49. localStorage.removeItem('dictList')
  50. localStorage.removeItem('dynamicMenuRoutes')
  51. localStorage.removeItem('routerList')
  52. router.options.isAddDynamicMenuRoutes = false
  53. }
  54. /**
  55. * 表单对象赋值:
  56. * 对目标对象存在且源对象同样存在的属性,全部覆盖;
  57. * 目标对象不存在但是源对象存在的属性, 全部丢弃;
  58. * 目标对象存在但是源对象不存在的属性,如果是字符串赋值为空串,其余类型赋值为undefined
  59. */
  60. export function recover (target, source) {
  61. if (target === undefined || target === null) { throw new TypeError('Cannot convert first argument to object') }
  62. var to = Object(target)
  63. if (source === undefined || source === null) { return to }
  64. var keysArray = Object.keys(Object(target))
  65. for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
  66. var nextKey = keysArray[nextIndex]
  67. var desc = Object.getOwnPropertyDescriptor(target, nextKey)
  68. if (desc !== undefined && desc.enumerable) {
  69. if (to.hasOwnProperty(nextKey)) {
  70. if (to[nextKey] instanceof Array) {
  71. to[nextKey] = source[nextKey]
  72. } else if (to[nextKey] instanceof Object) {
  73. recover(to[nextKey], source[nextKey])
  74. } else if (source[nextKey] !== undefined) {
  75. to[nextKey] = source[nextKey]
  76. } else if (typeof (to[nextKey]) === 'string') {
  77. to[nextKey] = ''
  78. } else {
  79. to[nextKey] = undefined
  80. }
  81. }
  82. }
  83. }
  84. return to
  85. }
  86. /**
  87. * 表单对象赋值:
  88. * 对目标对象存在且源对象同样存在的属性,全部覆盖;
  89. * 目标对象不存在但是源对象存在的属性, 全部丢弃;
  90. * 目标对象存在但是源对象不存在的属性,保留目标对象的属性不做处理
  91. */
  92. export function recoverNotNull (target, source) {
  93. if (target === undefined || target === null) { throw new TypeError('Cannot convert first argument to object') }
  94. var to = Object(target)
  95. if (source === undefined || source === null) { return to }
  96. var keysArray = Object.keys(Object(target))
  97. for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
  98. var nextKey = keysArray[nextIndex]
  99. var desc = Object.getOwnPropertyDescriptor(target, nextKey)
  100. if (desc !== undefined && desc.enumerable) {
  101. if (to.hasOwnProperty(nextKey)) {
  102. if (to[nextKey] instanceof Array) {
  103. to[nextKey] = source[nextKey]
  104. } else if (to[nextKey] instanceof Object) {
  105. recover(to[nextKey], source[nextKey])
  106. } else if (source[nextKey] !== undefined) {
  107. to[nextKey] = source[nextKey]
  108. }
  109. }
  110. }
  111. }
  112. return to
  113. }
  114. export function download (url, params) {
  115. $http({
  116. method: 'get',
  117. url: url,
  118. params: params,
  119. responseType: 'blob'
  120. }).then(response => {
  121. if (!response) {
  122. return
  123. }
  124. let link = document.createElement('a')
  125. link.href = window.URL.createObjectURL(new Blob([response.data]))
  126. link.target = '_blank'
  127. let filename = response.headers['content-disposition']
  128. link.download = decodeURI(filename)
  129. document.body.appendChild(link)
  130. link.click()
  131. document.body.removeChild(link)
  132. // eslint-disable-next-line handle-callback-err
  133. }).catch((error) => {
  134. })
  135. }
  136. export function downloadExcel (data, filename) {
  137. var blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}) // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
  138. var downloadElement = document.createElement('a')
  139. var href = window.URL.createObjectURL(blob) // 创建下载的链接
  140. downloadElement.href = href
  141. downloadElement.download = filename // 下载后文件名
  142. document.body.appendChild(downloadElement)
  143. downloadElement.click() // 点击下载
  144. document.body.removeChild(downloadElement) // 下载完成移除元素
  145. window.URL.revokeObjectURL(href) // 释放掉blob对象
  146. }
  147. export function downloadWord (data, filename) {
  148. var blob = new Blob([data], {type: 'application/msword,charset=utf-8'}) // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
  149. var downloadElement = document.createElement('a')
  150. var href = window.URL.createObjectURL(blob) // 创建下载的链接
  151. downloadElement.href = href
  152. downloadElement.download = filename // 下载后文件名
  153. document.body.appendChild(downloadElement)
  154. downloadElement.click() // 点击下载
  155. document.body.removeChild(downloadElement) // 下载完成移除元素
  156. window.URL.revokeObjectURL(href) // 释放掉blob对象
  157. }
  158. export function escapeHTML (a) {
  159. a = '' + a
  160. return a.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;')
  161. }
  162. /**
  163. * @function unescapeHTML 还原html脚本 < > & " '
  164. * @param a -
  165. * 字符串
  166. */
  167. export function unescapeHTML (a) {
  168. a = '' + a
  169. return a.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&apos;/g, "'")
  170. }
  171. export function printLogo () {
  172. console.info(
  173. '%c欢迎使用%c兴光评估系统平台',
  174. 'color: #ffffff; background: #000000; padding:5px 10px 5px 10px;font-size:40px;border-radius:12px 0 0 12px;', 'color: #000000; background: #FE9A00; padding:5px 10px;font-size:40px;border-radius:0 12px 12px 0;')
  175. }
  176. /**
  177. * 对象深拷贝
  178. */
  179. export function deepClone (data) {
  180. var type = getObjType(data)
  181. var obj
  182. if (type === 'array') {
  183. obj = []
  184. } else if (type === 'object') {
  185. obj = {}
  186. } else {
  187. // 不再具有下一层次
  188. return data
  189. }
  190. if (type === 'array') {
  191. for (var i = 0, len = data.length; i < len; i++) {
  192. data[i] = (function () {
  193. if (data[i] === 0) {
  194. return data[i]
  195. }
  196. return data[i]
  197. }())
  198. delete data[i].$parent
  199. obj.push(deepClone(data[i]))
  200. }
  201. } else if (type === 'object') {
  202. for (var key in data) {
  203. delete data.$parent
  204. obj[key] = deepClone(data[key])
  205. }
  206. }
  207. return obj
  208. };
  209. export function getObjType (obj) {
  210. var toString = Object.prototype.toString
  211. var map = {
  212. '[object Boolean]': 'boolean',
  213. '[object Number]': 'number',
  214. '[object String]': 'string',
  215. '[object Function]': 'function',
  216. '[object Array]': 'array',
  217. '[object Date]': 'date',
  218. '[object RegExp]': 'regExp',
  219. '[object Undefined]': 'undefined',
  220. '[object Null]': 'null',
  221. '[object Object]': 'object'
  222. }
  223. if (obj instanceof Element) {
  224. return 'element'
  225. }
  226. return map[toString.call(obj)]
  227. };
  228. export function validatenull (val) {
  229. // 特殊判断
  230. if (val && parseInt(val) === 0) return false
  231. var list = ['$parent']
  232. if (typeof val === 'boolean') {
  233. return false
  234. }
  235. if (typeof val === 'number') {
  236. return false
  237. }
  238. if (val instanceof Array) {
  239. if (val.length === 0) return true
  240. } else if (val instanceof Object) {
  241. val = (0, deepClone)(val)
  242. list.forEach(function (ele) {
  243. delete val[ele]
  244. })
  245. if (JSON.stringify(val) === '{}') return true
  246. } else {
  247. if (val === 'null' || val == null || val === 'undefined' || val === undefined || val === '') {
  248. return true
  249. }
  250. return false
  251. }
  252. return false
  253. }
  254. function handleImageAdded (file, Editor, cursorLocation, resetUploader) {
  255. // An example of using FormData
  256. // NOTE: Your key could be different such as:
  257. // formData.append('file', file)
  258. var formData = new FormData()
  259. formData.append('file', file)
  260. $http({
  261. url: '/sys/file/webupload/upload?uploadPath=/vueEditor',
  262. method: 'POST',
  263. data: formData,
  264. headers: { 'Content-Type': 'multipart/form-data' }
  265. })
  266. .then(result => {
  267. let url = result.data.url // Get url from response
  268. Editor.insertEmbed(cursorLocation, 'image', url)
  269. resetUploader()
  270. })
  271. .catch(err => {
  272. console.log(err)
  273. })
  274. }
  275. function hashCode (str) {
  276. var hash = 0
  277. if (str.length === 0) return hash
  278. for (let i = 0; i < str.length; i++) {
  279. let char = str.charCodeAt(i)
  280. hash = ((hash << 5) - hash) + char
  281. hash = hash & hash // Convert to 32bit integer
  282. }
  283. return hash
  284. }
  285. // 驼峰转下划线
  286. function toLine (name) {
  287. if (name.indexOf('.') < 0) {
  288. return name.replace(/([A-Z])/g, '_$1').toLowerCase()
  289. } else {
  290. return name
  291. }
  292. }
  293. export default {toLine, escapeHTML, hashCode, unescapeHTML, handleImageAdded, download, downloadExcel, downloadWord, recover, recoverNotNull, hasPermission, treeDataTranslate, printLogo, deepClone, validatenull}