vue中使用唯一标识uuid——uuid.v1()-时间戳uuid.v4()-随机数

Posted viceen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vue中使用唯一标识uuid——uuid.v1()-时间戳uuid.v4()-随机数相关的知识,希望对你有一定的参考价值。

vue中使用唯一标识uuid——uuid.v1()-时间戳、uuid.v4()-随机数

1、基本介绍

npm地址:https://www.npmjs.com/package/uuid#api

uuid在线生成器:http://uuid.bchrt.com/

uuid指通用唯一识别码

UUID 是 通用唯一识别码(Universally Unique Identifier)的缩写,是一种软件建构的标准,亦为开放软件基金会组织在分布式计算环境领域的一部分。其目的,是让分布式系统中的所有元素,都能有唯一的辨识信息,而不需要通过中央控制端来做辨识信息的指定。

UUID 是由一组32位数的16进制数字所构成,是故 UUID 理论上的总数为1632=2128,约等于3.4 x 10123。也就是说若每纳秒产生1百万个 UUID,要花100亿年才会将所有 UUID 用完

格式:

UUID 的十六个八位字节被表示为 32个十六进制数字,以连字号分隔的五组来显示,形式为 8-4-4-4-12,总共有 36个字符(即三十二个英数字母和四个连字号)。例如:

123e4567-e89b-12d3-a456-426655440000
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
  • 数字 M 的四位表示 UUID 版本,当前规范有5个版本,M可选值为1, 2, 3, 4, 5 ;
  • 数字 N 的一至四个最高有效位表示 UUID 变体( variant ),有固定的两位10xx因此只可能取值8, 9, a, b;

UUID版本通过 M 表示,当前规范有5个版本,可选值为1, 2, 3, 4, 5。这5个版本使用不同算法,利用不同的信息来产生 UUID,各版本有各自优势,适用于不同情景。具体使用的信息

2、使用

1、安装:

npm install uuid
npm install uuid --save
cnpm i -S vue-uuid

2、生成一个 UUID :

import  v4 as uuidv4  from 'uuid';
uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

使用 CommonJS 语法:

const  v4: uuidv4  = require('uuid');
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'

const uuid = require('uuid') //1、引包
console.log(uuid.v1()) //2、调用 98fc11a0-dde0-11e9-ade5-25202b3a2fba
vue中使用
全局引用

1、main.js中引入

import UUID from "vue-uuid";
Vue.use(UUID);

2、使用

console.log("this.$uuid.v1():", this.$uuid.v1());
// this.$uuid.v1():b1ef4cf0-ae0d-11eb-bed8-596efe8bfb0b
局部引用
import  uuid  from 'vue-uuid';

使用:

 uuid.v1()

完整

import  v4 as uuidv4  from ‘uuid’

const uuid = uuidv4() 
this.sessionId = uuid.v4()
console.log(this.sessionId)
node中使用uuid
# 下载
cnpm i -S uuid

使用

const uuid = require('uuid')
console.log("uuid.v4()", uuid.v4())

3、api参数

uuid.NILnil UUID字符串(全零)新进 [email protected]
uuid.parse()将UUID字符串转换为字节数组新进 [email protected]
uuid.stringify()将字节数组转换为UUID字符串新进 [email protected]
uuid.v1()创建版本1(时间戳)UUID
uuid.v3()创建版本3(带MD5的命名空间)UUID
uuid.v4()创建版本4(随机)UUID
uuid.v5()创建版本5(带SHA-1的命名空间)UUID
uuid.validate()测试字符串以查看它是否为有效的UUID新进 [email protected]
uuid.version()检测UUID的RFC版本新进 [email protected]

4、应用实例

实例1

全局使用

package.json

  "uuid": "^8.3.1",

main.js

import  v4 as uuidv4  from 'uuid';

// 全局方法挂载
Vue.prototype.uuidv4 = uuidv4

使用

click()
    var temp_event = this.uuidv4();
    console.log('temp_event',temp_event);
    eventBus.$on(temp_event,res=>
       this.getList();
       eventBus.$off(temp_event);
    );

实例2

页面刷新即生成一个新的 UUID :

uuid.v4() //直接加在页面的任意位置

打开页面/标签,即生成一个 UUID ,页面刷新 UUID 不会变。

打开页面,如果没有UUID则生成一个存入 sessionStorage ,如果有则直接读取sessionStorage中保存的UUID。

let uuid = sessionStorage.getItem('uuid');
if (!uuid) 
  sessionStorage.setItem('uuid',uuidv4());

UUID长期保存,清缓存后自动生成:

这样我们可以将uuid存入localStorage中,可以长期保存:

let uuid = localStorage.getItem('uuid');
if (!uuid) 
  localStorage.setItem('uuid',uuidv4());

增加登录验证,未登陆状态再生成 UUID:

if (getToken())//判断是否有 token
  sessionStorage.removeItem('uuid'); //如果有,清除 sessionStorage 中的 uuid
 else //未登录状态生成 uuid
  let uuid = sessionStorage.getItem('uuid');
  if (!uuid) 
    sessionStorage.setItem('uuid',uuidv4());
  

当然,也可以根据时间、设备信息、MD5和加盐(Salt)等方式生成更加精确的 UUID,大家可以根据自己的需求灵活运用。

csharp C#中的Java通用唯一标识符(UUID)实现

// Copyright © 2014 Rick Beerendonk. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;

namespace Beerendonk.Java
{
    /// <summary>
    /// Represents an immutable Java universally unique identifier (UUID).
    /// A UUID represents a 128-bit value.
    /// </summary>
    public struct Uuid : IEquatable<Uuid>
    {
        private readonly long leastSignificantBits;
        private readonly long mostSignificantBits;

        /// <summary>
        /// Constructs a new UUID using the specified data.
        /// </summary>
        /// <param name="mostSignificantBits">The most significant 64 bits of the UUID.</param>
        /// <param name="leastSignificantBits">The least significant 64 bits of the UUID</param>
        public Uuid(long mostSignificantBits, long leastSignificantBits)
        {
            this.mostSignificantBits = mostSignificantBits;
            this.leastSignificantBits = leastSignificantBits;
        }

        /// <summary>
        /// The least significant 64 bits of this UUID's 128 bit value.
        /// </summary>
        public long LeastSignificantBits
        {
            get { return leastSignificantBits; }
        }

        /// <summary>
        /// The most significant 64 bits of this UUID's 128 bit value.
        /// </summary>
        public long MostSignificantBits
        {
            get { return mostSignificantBits; }
        }

        /// <summary>
        /// Returns a value that indicates whether this instance is equal to a specified
        /// object.
        /// </summary>
        /// <param name="o">The object to compare with this instance.</param>
        /// <returns>true if o is a <paramref name="uuid"/> that has the same value as this instance; otherwise, false.</returns>
        public override bool Equals(object obj)
        {
            if (obj == null || !(obj is Uuid))
            {
                return false;
            }

            Uuid uuid = (Uuid)obj;

            return Equals(uuid);
        }

        /// <summary>
        /// Returns a value that indicates whether this instance and a specified <see cref="Uuid"/>
        /// object represent the same value.
        /// </summary>
        /// <param name="uuid">An object to compare to this instance.</param>
        /// <returns>true if <paramref name="uuid"/> is equal to this instance; otherwise, false.</returns>
        public bool Equals(Uuid uuid)
        {
            return this.mostSignificantBits == uuid.mostSignificantBits && this.leastSignificantBits == uuid.leastSignificantBits;
        }

        /// <summary>
        /// Returns the hash code for this instance.
        /// </summary>
        /// <returns>The hash code for this instance.</returns>
        public override int GetHashCode()
        {
            return ((Guid)this).GetHashCode();
        }

        /// <summary>
        /// <para></para>
        /// Returns a String object representing this UUID.
        /// </para>
        /// <para>
        /// The UUID string representation is as described by this BNF:
        /// </para>
        /// <code>
        ///   UUID                   =  "-"  "-"
        ///                             "-"
        ///                             "-"
        ///                            
        ///   time_low               = 4*
        ///   time_mid               = 2*
        ///   time_high_and_version  = 2*
        ///   variant_and_sequence   = 2*
        ///   node                   = 6*
        ///   hexOctet               = 
        ///   hexDigit               =
        ///         "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
        ///         | "a" | "b" | "c" | "d" | "e" | "f"
        ///         | "A" | "B" | "C" | "D" | "E" | "F"
        /// </code>
        /// </summary>
        /// <returns>A string representation of this UUID.</returns>
        public override string ToString()
        {
            return ((Guid)this).ToString();
        }

        /// <summary>Indicates whether the values of two specified <see cref="T:Uuid" /> objects are equal.</summary>
        /// <returns>true if <paramref name="a" /> and <paramref name="b" /> are equal; otherwise, false.</returns>
        /// <param name="a">The first object to compare. </param>
        /// <param name="b">The second object to compare. </param>
        public static bool operator ==(Uuid a, Uuid b)
        {
            return a.Equals(b);
        }

        /// <summary>Indicates whether the values of two specified <see cref="T:Uuid" /> objects are not equal.</summary>
        /// <returns>true if <paramref name="a" /> and <paramref name="b" /> are not equal; otherwise, false.</returns>
        /// <param name="a">The first object to compare. </param>
        /// <param name="b">The second object to compare. </param>
        public static bool operator !=(Uuid a, Uuid b)
        {
            return !a.Equals(b);
        }

        /// <summary>Converts an <see cref="T:Uuid"/> to a <see cref="T:System.Guid" />.</summary>
        /// <param name="value">The value to convert. </param>
        /// <returns>A <see cref="T:System.Guid"/> that represents the converted <see cref="T:Uuid" />.</returns>
        public static explicit operator Guid(Uuid uuid)
        {
            if (uuid == default(Uuid))
            {
                return default(Guid);
            }

            byte[] uuidMostSignificantBytes = BitConverter.GetBytes(uuid.mostSignificantBits);
            byte[] uuidLeastSignificantBytes = BitConverter.GetBytes(uuid.leastSignificantBits);
            byte[] guidBytes = new byte[16] {
                uuidMostSignificantBytes[4],
                uuidMostSignificantBytes[5],
                uuidMostSignificantBytes[6],
                uuidMostSignificantBytes[7],
                uuidMostSignificantBytes[2],
                uuidMostSignificantBytes[3],
                uuidMostSignificantBytes[0],
                uuidMostSignificantBytes[1],
                uuidLeastSignificantBytes[7],
                uuidLeastSignificantBytes[6],
                uuidLeastSignificantBytes[5],
                uuidLeastSignificantBytes[4],
                uuidLeastSignificantBytes[3],
                uuidLeastSignificantBytes[2],
                uuidLeastSignificantBytes[1],
                uuidLeastSignificantBytes[0]
            };

            return new Guid(guidBytes);
        }

        /// <summary>Converts a <see cref="T:System.Guid" /> to an <see cref="T:Uuid"/>.</summary>
        /// <param name="value">The value to convert. </param>
        /// <returns>An <see cref="T:Uuid"/> that represents the converted <see cref="T:System.Guid" />.</returns>
        public static implicit operator Uuid(Guid value)
        {
            if (value == default(Guid))
            {
                return default(Uuid);
            }

            byte[] guidBytes = value.ToByteArray();
            byte[] uuidBytes = new byte[16] {
                guidBytes[6],
                guidBytes[7],
                guidBytes[4],
                guidBytes[5],
                guidBytes[0],
                guidBytes[1],
                guidBytes[2],
                guidBytes[3],
                guidBytes[15],
                guidBytes[14],
                guidBytes[13],
                guidBytes[12],
                guidBytes[11],
                guidBytes[10],
                guidBytes[9],
                guidBytes[8]
            };

            return new Uuid(BitConverter.ToInt64(uuidBytes, 0), BitConverter.ToInt64(uuidBytes, 8));
        }

        /// <summary>
        /// Creates a UUID from the string standard representation as described in the <see cref="ToString()"/> method.
        /// </summary>
        /// <param name="input">A string that specifies a UUID.</param>
        /// <returns>A UUID with the specified value.</returns>
        /// <exception cref="ArgumentNullException">input is null.</exception>
        /// <exception cref="FormatException">input is not in a recognized format.</exception>
        public static Uuid FromString(string input)
        {
            return (Uuid)Guid.Parse(input);
        }
    }
}

以上是关于vue中使用唯一标识uuid——uuid.v1()-时间戳uuid.v4()-随机数的主要内容,如果未能解决你的问题,请参考以下文章

Node.js npm uuid

golang UUID v1,v2和v4

golang UUID v1,v2,v3,v4和v5

node-uuid

使用java.util.UUID生成唯一标识,为啥生成唯一标识的方法有些还需要参数?

生成唯一标识符 ,通用唯一标识符 UUID