You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

42 lines
1.7 KiB

  1. /**
  2. * 本算法来源于简书开源代码,详见:https://www.jianshu.com/p/fdbf293d0a85
  3. * 全局唯一标识符(uuid,Globally Unique Identifier),也称作 uuid(Universally Unique IDentifier)
  4. * 一般用于多个组件之间,给它一个唯一的标识符,或者v-for循环的时候,如果使用数组的index可能会导致更新列表出现问题
  5. * 最可能的情况是左滑删除item或者对某条信息流"不喜欢"并去掉它的时候,会导致组件内的数据可能出现错乱
  6. * v-for的时候,推荐使用后端返回的id而不是循环的index
  7. * @param {Number} len uuid的长度
  8. * @param {Boolean} firstU 将返回的首字母置为"u"
  9. * @param {Nubmer} radix 生成uuid的基数(意味着返回的字符串都是这个基数),2-二进制,8-八进制,10-十进制,16-十六进制
  10. */
  11. function guid(len = 32, firstU = true, radix = null) {
  12. let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  13. let uuid = [];
  14. radix = radix || chars.length;
  15. if (len) {
  16. // 如果指定uuid长度,只是取随机的字符,0|x为位运算,能去掉x的小数位,返回整数位
  17. for (let i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
  18. } else {
  19. let r;
  20. // rfc4122标准要求返回的uuid中,某些位为固定的字符
  21. uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
  22. uuid[14] = '4';
  23. for (let i = 0; i < 36; i++) {
  24. if (!uuid[i]) {
  25. r = 0 | Math.random() * 16;
  26. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  27. }
  28. }
  29. }
  30. // 移除第一个字符,并用u替代,因为第一个字符为数值时,该guuid不能用作id或者class
  31. if (firstU) {
  32. uuid.shift();
  33. return 'u' + uuid.join('');
  34. } else {
  35. return uuid.join('');
  36. }
  37. }
  38. export default guid;