• vue中常用的公共方法


    1. /**
    2. * @Event 方法
    3. * @description: 日期格式化
    4. * */
    5. export function parseTime(time, pattern) {
    6. if (arguments.length === 0 || !time) {
    7. return null;
    8. }
    9. const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
    10. let date;
    11. if (typeof time === "object") {
    12. date = time;
    13. } else {
    14. if (typeof time === "string" && /^[0-9]+$/.test(time)) {
    15. time = parseInt(time);
    16. } else if (typeof time === "string") {
    17. time = time
    18. .replace(new RegExp(/-/gm), "/")
    19. .replace("T", " ")
    20. .replace(new RegExp(/\.[\d]{3}/gm), "");
    21. }
    22. if (typeof time === "number" && time.toString().length === 10) {
    23. time = time * 1000;
    24. }
    25. date = new Date(time);
    26. }
    27. const formatObj = {
    28. y: date.getFullYear(),
    29. m: date.getMonth() + 1,
    30. d: date.getDate(),
    31. h: date.getHours(),
    32. i: date.getMinutes(),
    33. s: date.getSeconds(),
    34. a: date.getDay(),
    35. };
    36. const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    37. let value = formatObj[key];
    38. // Note: getDay() returns 0 on Sunday
    39. if (key === "a") {
    40. return ["日", "一", "二", "三", "四", "五", "六"][value];
    41. }
    42. if (result.length > 0 && value < 10) {
    43. value = "0" + value;
    44. }
    45. return value || 0;
    46. });
    47. return time_str;
    48. }
    49. /**
    50. * @Event 方法
    51. * @description: 表单重置
    52. * */
    53. export function resetForm(refName) {
    54. if (this.$refs[refName]) {
    55. this.$refs[refName].resetFields();
    56. }
    57. }
    58. /**
    59. * @Event 方法
    60. * @description: 添加日期范围
    61. * */
    62. export function addDateRange(params, dateRange, propName) {
    63. const search = params;
    64. search.params =
    65. typeof search.params === "object" &&
    66. search.params !== null &&
    67. !Array.isArray(search.params)
    68. ? search.params
    69. : {};
    70. dateRange = Array.isArray(dateRange) ? dateRange : [];
    71. if (typeof propName === "undefined") {
    72. search.params["beginTime"] = dateRange[0];
    73. search.params["endTime"] = dateRange[1];
    74. } else {
    75. search.params["begin" + propName] = dateRange[0];
    76. search.params["end" + propName] = dateRange[1];
    77. }
    78. return search;
    79. }
    80. /**
    81. * @Event 方法
    82. * @description: 回显数据字典
    83. * */
    84. export function selectDictLabel(datas, value) {
    85. if (value === undefined) {
    86. return "";
    87. }
    88. var actions = [];
    89. Object.keys(datas).some((key) => {
    90. if (datas[key].value == "" + value) {
    91. actions.push(datas[key].label);
    92. return true;
    93. }
    94. });
    95. if (actions.length === 0) {
    96. actions.push(value);
    97. }
    98. return actions.join("");
    99. }
    100. /**
    101. * @Event 方法
    102. * @description: 回显数据字典(字符串数组)
    103. * */
    104. export function selectDictLabels(datas, value, separator) {
    105. if (value === undefined) {
    106. return "";
    107. }
    108. var actions = [];
    109. var currentSeparator = undefined === separator ? "," : separator;
    110. var temp = value.split(currentSeparator);
    111. Object.keys(value.split(currentSeparator)).some((val) => {
    112. var match = false;
    113. Object.keys(datas).some((key) => {
    114. if (datas[key].value == "" + temp[val]) {
    115. actions.push(datas[key].label + currentSeparator);
    116. match = true;
    117. }
    118. });
    119. if (!match) {
    120. actions.push(temp[val] + currentSeparator);
    121. }
    122. });
    123. return actions.join("").substring(0, actions.join("").length - 1);
    124. }
    125. /**
    126. * @Event 方法
    127. * @description: 字符串格式化(%s )
    128. * */
    129. export function sprintf(str) {
    130. var args = arguments;
    131. var flag = true;
    132. var i = 1;
    133. str = str.replace(/%s/g, function () {
    134. var arg = args[i++];
    135. if (typeof arg === "undefined") {
    136. flag = false;
    137. return "";
    138. }
    139. return arg;
    140. });
    141. return flag ? str : "";
    142. }
    143. /**
    144. * @Event 方法
    145. * @description: 转换字符串,undefined,null等转化为""
    146. * */
    147. export function parseStrEmpty(str) {
    148. if (!str || str == "undefined" || str == "null") {
    149. return "";
    150. }
    151. return str;
    152. }
    153. /**
    154. * @Event 方法
    155. * @description: 数据合并
    156. * */
    157. export function mergeRecursive(source, target) {
    158. for (var p in target) {
    159. try {
    160. if (target[p].constructor == Object) {
    161. source[p] = mergeRecursive(source[p], target[p]);
    162. } else {
    163. source[p] = target[p];
    164. }
    165. } catch (e) {
    166. source[p] = target[p];
    167. }
    168. }
    169. return source;
    170. }
    171. /**
    172. * 构造树型结构数据
    173. * @param {*} data 数据源
    174. * @param {*} id id字段 默认 'id'
    175. * @param {*} parentId 父节点字段 默认 'parentId'
    176. * @param {*} children 孩子节点字段 默认 'children'
    177. */
    178. export function handleTree(data, id, parentId, children) {
    179. const config = {
    180. id: id || "id",
    181. parentId: parentId || "parentId",
    182. childrenList: children || "children",
    183. };
    184. var childrenListMap = {};
    185. var nodeIds = {};
    186. var tree = [];
    187. for (const d of data) {
    188. const parentId = d[config.parentId];
    189. if (childrenListMap[parentId] == null) {
    190. childrenListMap[parentId] = [];
    191. }
    192. nodeIds[d[config.id]] = d;
    193. childrenListMap[parentId].push(d);
    194. }
    195. for (const d of data) {
    196. const parentId = d[config.parentId];
    197. if (nodeIds[parentId] == null) {
    198. tree.push(d);
    199. }
    200. }
    201. for (const t of tree) {
    202. adaptToChildrenList(t);
    203. }
    204. function adaptToChildrenList(o) {
    205. if (childrenListMap[o[config.id]] !== null) {
    206. o[config.childrenList] = childrenListMap[o[config.id]];
    207. }
    208. if (o[config.childrenList]) {
    209. for (const c of o[config.childrenList]) {
    210. adaptToChildrenList(c);
    211. }
    212. }
    213. }
    214. return tree;
    215. }
    216. /**
    217. * 参数处理
    218. * @param {*} params 参数
    219. */
    220. export function tansParams(params) {
    221. let result = "";
    222. for (const propName of Object.keys(params)) {
    223. const value = params[propName];
    224. var part = encodeURIComponent(propName) + "=";
    225. if (value !== null && typeof value !== "undefined") {
    226. if (typeof value === "object") {
    227. for (const key of Object.keys(value)) {
    228. if (value[key] !== null && typeof value[key] !== "undefined") {
    229. const params = propName + "[" + key + "]";
    230. var subPart = encodeURIComponent(params) + "=";
    231. result += subPart + encodeURIComponent(value[key]) + "&";
    232. }
    233. }
    234. } else {
    235. result += part + encodeURIComponent(value) + "&";
    236. }
    237. }
    238. }
    239. return result;
    240. }
    241. /**
    242. * @Event 方法
    243. * @description: 验证是否为blob格式
    244. * */
    245. export async function blobValidate(data) {
    246. try {
    247. const text = await data.text();
    248. JSON.parse(text);
    249. return false;
    250. } catch (error) {
    251. return true;
    252. }
    253. }
    254. /**
    255. * @desc post请求 请求体转拼接
    256. * @param param - 需要转换的对象
    257. * @returns 转换后的对象
    258. */
    259. export function changePostParam(param) {
    260. return JSON.stringify(param)
    261. .replace(/:/g, "=")
    262. .replace(/,/g, "&")
    263. .replace(/{/g, "?")
    264. .replace(/}/g, "")
    265. .replace(/"/g, "");
    266. }
    267. /**
    268. * @Event 方法
    269. * @description: 数字每三位截断
    270. * @param: num
    271. * addCommas("1234567489") -> 1,234,567,489
    272. * */
    273. export function addCommas(num) {
    274. return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    275. }
    276. /**
    277. * @Event 方法
    278. * @description: 获取当前时间 (2023-08-15 10:35:30)
    279. * */
    280. export function getCurrentTime() {
    281. function formatDate(value) {
    282. return value < 10 ? `0${value}` : value;
    283. }
    284. const date = new Date();
    285. const year = date.getFullYear();
    286. const month = formatDate(date.getMonth() + 1);
    287. const day = formatDate(date.getDate());
    288. const hour = formatDate(date.getHours());
    289. const minute = formatDate(date.getMinutes());
    290. const second = formatDate(date.getSeconds());
    291. return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    292. }
    293. /**
    294. * @Event 方法
    295. * @description: 获取最近一周的时间 ["2023-08-08 11:45:50", "2023-08-15 11:45:50"]
    296. * */
    297. export function getAWeek() {
    298. const now = new Date();
    299. const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
    300. const endDate = formatDate(now);
    301. const startDate = formatDate(sevenDaysAgo);
    302. // console.log(`起始日期时间:${startDate},结束日期时间:${endDate}`);
    303. function formatDate(date) {
    304. const year = date.getFullYear();
    305. const month = formatNumber(date.getMonth() + 1);
    306. const day = formatNumber(date.getDate());
    307. const hours = formatNumber(date.getHours());
    308. const minutes = formatNumber(date.getMinutes());
    309. const seconds = formatNumber(date.getSeconds());
    310. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    311. }
    312. function formatNumber(num) {
    313. return num > 9 ? num : `0${num}`;
    314. }
    315. return [startDate, endDate];
    316. }
    317. // 节流
    318. export function throttleFun(fn, wait = 500) {
    319. let last, now;
    320. return function () {
    321. now = Date.now();
    322. if (last && now - last < wait) {
    323. last = now;
    324. } else {
    325. last = now;
    326. fn.call(this, ...arguments);
    327. }
    328. };
    329. }
    330. // 防抖
    331. export function debounceFun(fn, wait = 500) {
    332. let timer;
    333. return function () {
    334. let context = this;
    335. let args = arguments;
    336. if (timer) clearTimeout(timer);
    337. timer = setTimeout(() => {
    338. fn.apply(context, args);
    339. }, wait);
    340. };
    341. }
    342. /**
    343. * @Event 方法
    344. * @description: post导出表格数据
    345. * @param: formData: 传递的参数
    346. * url: 导出的接口地址
    347. * */
    348. import axios from "axios";
    349. import { Loading, Message } from "element-ui";
    350. import { getToken } from "./auth";
    351. export function downloadPost(formData, url) {
    352. let downloadLoadingInstance;
    353. downloadLoadingInstance = Loading.service({
    354. text: "正在下载数据,请稍候",
    355. spinner: "el-icon-loading",
    356. background: "rgba(0, 0, 0, 0.7)",
    357. });
    358. return axios({
    359. method: "post",
    360. url: process.env.VUE_APP_BASE_API + url, // 请求地址
    361. data: formData, // 参数
    362. responseType: "blob", // 表明返回服务器返回的数据类型
    363. headers: {
    364. AuthorizationSys: getToken(),
    365. "Content-Type": "application/json",
    366. },
    367. }).then(async (data) => {
    368. const isLogin = await blobValidate(data.data);
    369. const fileNameEncode =
    370. data.headers["content-disposition"].split("filename=")[1];
    371. var fileName = decodeURIComponent(fileNameEncode);
    372. if (isLogin) {
    373. const blob = new Blob([data.data]);
    374. saveAs(blob, fileName);
    375. } else {
    376. const resText = await data.text();
    377. const rspObj = JSON.parse(resText);
    378. const errMsg = rspObj.message;
    379. Message.error(errMsg);
    380. }
    381. downloadLoadingInstance.close();
    382. });
    383. }
    384. /**
    385. * @Event 方法
    386. * @description: 获取最近num天的时间
    387. * @param: num: 最近的天数, isDateTime: 是否需要时分秒(默认是)
    388. * isDateTime 最终格式如下:["2023-08-08 11:45:50", "2023-08-15 11:45:50"]
    389. * !isDateTime 最终格式如下:["2023-08-08", "2023-08-15"]
    390. * */
    391. export function getLastNumDay(num, isDateTime = true) {
    392. const now = new Date();
    393. const sevenDaysAgo = new Date(now.getTime() - num * 24 * 60 * 60 * 1000);
    394. const endDate = formatDate(now);
    395. const startDate = formatDate(sevenDaysAgo);
    396. // console.log(`起始日期时间:${startDate},结束日期时间:${endDate}`);
    397. function formatDate(date) {
    398. const year = date.getFullYear();
    399. const month = formatNumber(date.getMonth() + 1);
    400. const day = formatNumber(date.getDate());
    401. const hours = formatNumber(date.getHours());
    402. const minutes = formatNumber(date.getMinutes());
    403. const seconds = formatNumber(date.getSeconds());
    404. return isDateTime
    405. ? `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    406. : `${year}-${month}-${day}`;
    407. }
    408. function formatNumber(num) {
    409. return num > 9 ? num : `0${num}`;
    410. }
    411. return [startDate, endDate];
    412. }
    413. /**
    414. * @Event 方法
    415. * @description: 获取前num天的时间(格式为:"2023-09-26")
    416. * @param: num 几天前
    417. * */
    418. export function getLastDay(num) {
    419. var time = new Date().getTime() - num * 24 * 60 * 60 * 1000;
    420. var yesterday = new Date(time);
    421. var month = yesterday.getMonth();
    422. var day = yesterday.getDate();
    423. yesterday =
    424. yesterday.getFullYear() +
    425. "-" +
    426. (yesterday.getMonth() > 9
    427. ? yesterday.getMonth() + 1
    428. : "0" + (yesterday.getMonth() + 1)) +
    429. "-" +
    430. (yesterday.getDate() > 9 ? yesterday.getDate() : "0" + yesterday.getDate());
    431. return yesterday;
    432. }
    433. /**
    434. * @Event 判断对象是否为空
    435. * @description:
    436. * @author: mhf
    437. * @time: 2023-10-25 15:17:48
    438. **/
    439. export function isEmptyObject(obj) {
    440. return Object.keys(obj).length === 0 && obj.constructor === Object;
    441. }

  • 相关阅读:
    使用数据库维护数据来源,动态切换数据源的工具:dynamic-datasource
    OpenGLES:绘制一个混色旋转的3D圆锥
    【MySQL】MySQL中如何实现分页操作
    一个好的聆听者
    金仓数据库KStudio使用手册(5. PLSQL开发)
    【Qt图形视图框架】QGraphicsView分析
    LeetCode 6190. 找到所有好下标
    Microsoft Releases .NET 7新功能
    【RCNN系列】Fast RCNN论文总结
    大三学生HTML期末作业,网页制作作业——HTML+CSS+JavaScript饮品饮料茶(7页)
  • 原文地址:https://blog.csdn.net/m0_74149462/article/details/134035934