Skip to content
On this page

mockValue生成随机字符串

Hidden Title

基础用法:mockValue()

基础用法

说明

mockValue 用于生成随机字符串,也内置了手机号、邮箱、时间、数字、IP、端口和选项数组取值等模式。它常用于 mock 数据、临时标识、表单默认值和演示数据。

调用形式

ts
mockValue()
mockValue(type)
mockValue(type, length)
mockValue(type, length, options)
mockValue(optionsArray, length, options)
mockValue()
mockValue(type)
mockValue(type, length)
mockValue(type, length, options)
mockValue(optionsArray, length, options)

参数说明

参数类型必填默认值说明
typestring | Array<{ label: string; value: any }>''生成模式。不传时生成普通随机字符串;传数组时随机返回某一项或该项的 value
lengthnumber4普通随机字符串或 number 模式的长度。
optionsMockValueOptions{}不同模式下的额外配置。

内置 type

type返回值说明
''string生成由去除易混字符后的大小写字母和数字组成的随机字符串。
'phone'string生成 130/131/132/133/135/136/137/138/170/187/189 等前缀开头的手机号。
'email'string生成随机字符串并追加邮箱后缀。
'time'string生成随机字符串,再追加当前时间。
'number'number生成指定长度的正整数,不包含 0
'ip'string生成 10.0.11.x 格式的 IP。
'port'number生成 1-65535 范围内的端口号。
Arrayany从数组中随机取一项;如果数组项有 value 字段,返回 value

MockValueOptions 字段:

字段类型默认值说明
emailStrstring'@qq.com'email 模式下追加的邮箱后缀。
timeStrstring'{y}-{m}-{d} {h}:{i}:{s}'time 模式下追加的时间格式,格式规则同 formatTime
startStrstring''生成结果前缀,普通随机字符串、emailtime 模式会使用。
optionsIndexnumber | nullnull数组选项模式下指定固定索引;不传时随机取值。

返回值

根据 type 返回 stringnumber 或数组项的 value。传空数组时返回空字符串。

常用场景

ts
mockValue()
// 'aB3d'

mockValue('number', 6)
// 483921

mockValue('email', 6, { emailStr: '@example.com' })
// 'xY3kP2@example.com'

mockValue('time', 4, { startStr: 'task-', timeStr: '{h}:{i}:{s}' })
// 'task-aB3d 09:30:12'

mockValue(
  [
    { label: '启用', value: 1 },
    { label: '禁用', value: 0 },
  ],
  4,
  { optionsIndex: 0 },
)
// 1
mockValue()
// 'aB3d'

mockValue('number', 6)
// 483921

mockValue('email', 6, { emailStr: '@example.com' })
// 'xY3kP2@example.com'

mockValue('time', 4, { startStr: 'task-', timeStr: '{h}:{i}:{s}' })
// 'task-aB3d 09:30:12'

mockValue(
  [
    { label: '启用', value: 1 },
    { label: '禁用', value: 0 },
  ],
  4,
  { optionsIndex: 0 },
)
// 1

注意事项

mockValue 使用 Math.random(),适合业务展示和 mock 数据,不适合作为密码学安全随机数。number 模式不会生成包含 0 的数字。

函数源码

mockValue

来源:packages/utils/src/base.ts

/**
 * 生成随机字符串,也支持手机号、邮箱、时间、数字、IP、端口等特殊模式。
 *
 * @param type 生成模式,支持空字符串、`phone`、`email`、`time`、`number`、`ip`、`port`,也支持传选项数组。
 * @param length 随机字符串或数字的长度,默认 `4`。
 * @param options 额外配置。
 * @returns 生成结果。
 *
 * @example
 * mockValue()
 * // => 'aB3d'
 *
 * @example
 * mockValue('phone')
 * // => '13603312460'
 *
 * @example
 * mockValue('time', 0, { startStr: 'andy', timeStr: '{h}:{i}:{s}' })
 */
export function mockValue(
  type: string | Array<MockValueOptionItem> = '',
  length = 4,
  options: MockValueOptions = {},
): string | number | any {
  const { emailStr = '@qq.com', timeStr = '{y}-{m}-{d} {h}:{i}:{s}', startStr = '', optionsIndex = null } = options

  // 辅助函数:判断是否为ref对象
  function isRef(obj: any): obj is Ref<any> {
    return obj && typeof obj === 'object' && obj._isRef === true
  }

  // 辅助函数:获取ref的实际值
  function unref<T>(ref: Ref<T> | T): T {
    return isRef(ref) ? ref.value : ref
  }

  // 辅助函数:生成随机数
  function random(min: number, max: number): number {
    return Math.floor(Math.random() * (max - min + 1) + min)
  }

  // 解包可能为ref的参数
  type = unref(type)

  // 处理数组类型参数(下拉框选项)
  if (Array.isArray(type)) {
    if (type.length === 0) return ''

    const randIndex = optionsIndex ?? random(0, type.length - 1)
    const selectedItem = type[randIndex]

    // 如果数组项是对象且有value属性,则返回value
    if (typeof selectedItem === 'object' && selectedItem !== null && 'value' in selectedItem) {
      return selectedItem.value
    }

    // 否则直接返回数组项
    return selectedItem
  }

  // 生成随机字符串
  let randomChars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  let result = startStr

  // 生成手机号
  if (type === 'phone') {
    const prefixes = ['130', '131', '132', '133', '135', '136', '137', '138', '170', '187', '189']
    result = prefixes[random(0, prefixes.length - 1)]

    for (let i = 0; i < 8; i++) {
      result += Math.floor(Math.random() * 10)
    }
    return result
  }

  // 生成邮箱
  if (type === 'email') {
    result = mockValue(startStr, length) + emailStr
    return result
  }

  // 生成时间
  if (type === 'time') {
    return mockValue(startStr, length, options) + ' ' + formatTime(new Date(), timeStr)
  }

  // 生成数字
  if (type === 'number') {
    const numChars = '123456789'
    result = ''

    for (let i = 0; i < length; i++) {
      result += numChars[random(0, numChars.length - 1)]
    }
    return Number(result)
  }

  // 生成IP地址
  if (type === 'ip') {
    const randomNum = random(1, 99)
    return `10.0.11.${randomNum}`
  }

  // 生成端口号
  if (type === 'port') {
    return random(1, 65535)
  }

  // 生成普通随机字符串
  for (let i = 0; i < length; i++) {
    result += randomChars[random(0, randomChars.length - 1)]
  }

  return result
}

思云博智私有前端组件库