如何在 vue 中生成预订代码?

How can I generate booking code in the vue?

我这样试:

methods: {
    generateCode () {
      const letters = '1217CHELS323412eafoo'
      const uniqueId = function () {
        let text = ''
        for (let i = 0; i < 6; i++) {
          text += letters.charAt(Math.floor(Math.random() * letters.length))
        }
        return text
      }
      return uniqueId()
    }
}

一些结果示例::L1LE3Co23H1fHeLe34

这段代码完美吗?我的意思是每次调用这个方法,它肯定会生成一个唯一的预订代码

你的字母选择很少,而且你只生成6个字符的代码,我做了一个简单的脚本来检查你需要生成多少次代码才能匹配LS73ea

12787899 times
20141743 times
31479934 times
18819863 times
30361586 times
5533616 times
6495725 times
13431128 times
29765633 times
18367311 times

重复的可能性很高。

我不明白为什么要在 letters 中包含相同的字符。相反,做这样的事情:

methods: {
    generateCode () {
      // Alphanumeric
      const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
      const uniqueId = function () {
        let text = ''
        for (let i = 0; i < 8; i++) {
          text += characters.charAt(Math.floor(Math.random() * characters.length))
        }
        return text
      }
      return uniqueId()
    }
}

该函数会生成类似HrsK9wgF的代码,并且重复的机会更少,如果你想把它降低得更低,你也可以:

  1. 在字母选择中添加更多字符,例如符号 (-_)
  2. 增加生成代码长度

作为参考,Youtube的视频id使用了A-Za-z0-9-_来选择角色,并且有11 个字符长度。

除此之外,您确定要在前端应用程序上生成 ID 吗?它似乎应该在您的后端应用程序上生成。