index.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. filename = filename + '.xls'
  138. var blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}) // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
  139. var downloadElement = document.createElement('a')
  140. var href = window.URL.createObjectURL(blob) // 创建下载的链接
  141. downloadElement.href = href
  142. downloadElement.download = filename // 下载后文件名
  143. document.body.appendChild(downloadElement)
  144. downloadElement.click() // 点击下载
  145. document.body.removeChild(downloadElement) // 下载完成移除元素
  146. window.URL.revokeObjectURL(href) // 释放掉blob对象
  147. }
  148. export function downloadWord (data, filename) {
  149. var blob = new Blob([data], {type: 'application/msword,charset=utf-8'}) // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
  150. var downloadElement = document.createElement('a')
  151. var href = window.URL.createObjectURL(blob) // 创建下载的链接
  152. downloadElement.href = href
  153. downloadElement.download = filename // 下载后文件名
  154. document.body.appendChild(downloadElement)
  155. downloadElement.click() // 点击下载
  156. document.body.removeChild(downloadElement) // 下载完成移除元素
  157. window.URL.revokeObjectURL(href) // 释放掉blob对象
  158. }
  159. export function escapeHTML (a) {
  160. a = '' + a
  161. return a.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&apos;')
  162. }
  163. /**
  164. * @function unescapeHTML 还原html脚本 < > & " '
  165. * @param a -
  166. * 字符串
  167. */
  168. export function unescapeHTML (a) {
  169. a = '' + a
  170. return a.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&apos;/g, "'")
  171. }
  172. export function printLogo () {
  173. console.info(
  174. '%c欢迎使用%c兴光系统平台',
  175. '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;')
  176. }
  177. /**
  178. * 对象深拷贝
  179. */
  180. export function deepClone (data) {
  181. var type = getObjType(data)
  182. var obj
  183. if (type === 'array') {
  184. obj = []
  185. } else if (type === 'object') {
  186. obj = {}
  187. } else {
  188. // 不再具有下一层次
  189. return data
  190. }
  191. if (type === 'array') {
  192. for (var i = 0, len = data.length; i < len; i++) {
  193. data[i] = (function () {
  194. if (data[i] === 0) {
  195. return data[i]
  196. }
  197. return data[i]
  198. }())
  199. delete data[i].$parent
  200. obj.push(deepClone(data[i]))
  201. }
  202. } else if (type === 'object') {
  203. for (var key in data) {
  204. delete data.$parent
  205. obj[key] = deepClone(data[key])
  206. }
  207. }
  208. return obj
  209. };
  210. export function getObjType (obj) {
  211. var toString = Object.prototype.toString
  212. var map = {
  213. '[object Boolean]': 'boolean',
  214. '[object Number]': 'number',
  215. '[object String]': 'string',
  216. '[object Function]': 'function',
  217. '[object Array]': 'array',
  218. '[object Date]': 'date',
  219. '[object RegExp]': 'regExp',
  220. '[object Undefined]': 'undefined',
  221. '[object Null]': 'null',
  222. '[object Object]': 'object'
  223. }
  224. if (obj instanceof Element) {
  225. return 'element'
  226. }
  227. return map[toString.call(obj)]
  228. };
  229. export function validatenull (val) {
  230. // 特殊判断
  231. if (val && parseInt(val) === 0) return false
  232. var list = ['$parent']
  233. if (typeof val === 'boolean') {
  234. return false
  235. }
  236. if (typeof val === 'number') {
  237. return false
  238. }
  239. if (val instanceof Array) {
  240. if (val.length === 0) return true
  241. } else if (val instanceof Object) {
  242. val = (0, deepClone)(val)
  243. list.forEach(function (ele) {
  244. delete val[ele]
  245. })
  246. if (JSON.stringify(val) === '{}') return true
  247. } else {
  248. if (val === 'null' || val == null || val === 'undefined' || val === undefined || val === '') {
  249. return true
  250. }
  251. return false
  252. }
  253. return false
  254. }
  255. function handleImageAdded (file, Editor, cursorLocation, resetUploader) {
  256. // An example of using FormData
  257. // NOTE: Your key could be different such as:
  258. // formData.append('file', file)
  259. var formData = new FormData()
  260. formData.append('file', file)
  261. $http({
  262. url: '/sys/file/webupload/upload?uploadPath=/vueEditor',
  263. method: 'POST',
  264. data: formData,
  265. headers: { 'Content-Type': 'multipart/form-data' }
  266. })
  267. .then(result => {
  268. let url = result.data.url // Get url from response
  269. Editor.insertEmbed(cursorLocation, 'image', url)
  270. resetUploader()
  271. })
  272. .catch(err => {
  273. console.log(err)
  274. })
  275. }
  276. function hashCode (str) {
  277. var hash = 0
  278. if (str.length === 0) return hash
  279. for (let i = 0; i < str.length; i++) {
  280. let char = str.charCodeAt(i)
  281. hash = ((hash << 5) - hash) + char
  282. hash = hash & hash // Convert to 32bit integer
  283. }
  284. return hash
  285. }
  286. // 驼峰转下划线
  287. function toLine (name) {
  288. if (name.indexOf('.') < 0) {
  289. return name.replace(/([A-Z])/g, '_$1').toLowerCase()
  290. } else {
  291. return name
  292. }
  293. }
  294. export default {toLine, escapeHTML, hashCode, unescapeHTML, handleImageAdded, download, downloadExcel, downloadWord, recover, recoverNotNull, hasPermission, treeDataTranslate, printLogo, deepClone, validatenull}