common.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import Vue from 'vue';
  2. import { AxiosResponse } from 'axios';
  3. // 处理所有后端返回的数据
  4. export function processReturn(res: AxiosResponse<ServerRes>) {
  5. // code 0:成功 1:错误 2:后端报错
  6. const { code, msg, data } = res.data;
  7. if (code) {
  8. Vue.prototype.$message.error(msg);
  9. return;
  10. }
  11. if (msg) {
  12. Vue.prototype.$message.success(msg);
  13. }
  14. return data;
  15. }
  16. // 判断一个字符串是否包含另外一个字符串
  17. export function isContainStr(str1: string, str2: string) {
  18. return str2.indexOf(str1) >= 0;
  19. }
  20. /**
  21. * 屏蔽词
  22. * @param text 文本
  23. */
  24. export function parseText(text: string) {
  25. return text;
  26. }
  27. /**
  28. * 判断是否URL
  29. * @param text 文本
  30. */
  31. export function isUrl(text: string) {
  32. // 解析网址
  33. // eslint-disable-next-line no-useless-escape
  34. const UrlReg = new RegExp(/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/);
  35. return UrlReg.test(text);
  36. }
  37. /**
  38. * 消息时间格式化
  39. * @param time
  40. */
  41. export function formatTime(time: number) {
  42. const moment = Vue.prototype.$moment;
  43. // 大于昨天
  44. if (moment().add(-1, 'days').startOf('day') > time) {
  45. return moment(time).format('M/D HH:mm');
  46. }
  47. // 昨天
  48. if (moment().startOf('day') > time) {
  49. return `昨天 ${moment(time).format('HH:mm')}`;
  50. }
  51. // 大于五分钟不显示秒
  52. // if (new Date().valueOf() > time + 300000) {
  53. // return moment(time).format('HH:mm');
  54. // }
  55. return moment(time).format('HH:mm');
  56. }
  57. /**
  58. * 群名/用户名校验
  59. * @param name
  60. */
  61. export function nameVerify(name: string): boolean {
  62. const nameReg = /^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/;
  63. if (name.length === 0) {
  64. Vue.prototype.$message.error('请输入名字');
  65. return false;
  66. }
  67. if (!nameReg.test(name)) {
  68. Vue.prototype.$message.error('名字只含有汉字、字母、数字和下划线 不能以下划线开头和结尾');
  69. return false;
  70. }
  71. if (name.length > 16) {
  72. Vue.prototype.$message.error('名字太长');
  73. return false;
  74. }
  75. return true;
  76. }
  77. /**
  78. * 密码校验
  79. * @param password
  80. */
  81. export function passwordVerify(password: string): boolean {
  82. const passwordReg = /^\w+$/gis;
  83. if (password.length === 0) {
  84. Vue.prototype.$message.error('请输入密码');
  85. return false;
  86. }
  87. if (!passwordReg.test(password)) {
  88. Vue.prototype.$message.error('密码只含有字母、数字和下划线');
  89. return false;
  90. }
  91. if (password.length > 16) {
  92. Vue.prototype.$message.error('密码最多16位,请重新输入');
  93. return false;
  94. }
  95. return true;
  96. }