yaogengzhu / daily-share

个人博客记录、内容在issues
30 stars 4 forks source link

mockjs 基础用法、随机名字、随机手机号、拓展语法 (2022-09-27) #175

Open yaogengzhu opened 2 years ago

yaogengzhu commented 2 years ago
// 使用 Mock
const Mock = require("mockjs");
// 拓展mockjs
Mock.Random.extend({
  phone: function () {
    var phonePrefixs = ["132", "135", "189"]; // 自己写前缀哈
    return this.pick(phonePrefixs) + Mock.mock(/\d{8}/); //Number()
  },
});

const data = Mock.mock({
  // 属性 list 的值是一个数组,其中含有 1 到 10 个元素
  "list|10-20": [
    {
      // 属性 id 是一个自增数,起始值为 1,每次增 1
      "id|+1": 1,
      "number|+1": 202,
      phone: "@phone",
      name: "@cname()",
    },
  ],
});
// 输出结果
console.log(data.list);

result

[
  { id: 1, number: 202, phone: '13562523841', name: '武艳' },
  { id: 2, number: 203, phone: '13546977222', name: '阎伟' },
  { id: 3, number: 204, phone: '13542564689', name: '傅敏' },
  { id: 4, number: 205, phone: '13587824628', name: '苏桂英' },
  { id: 5, number: 206, phone: '13592274431', name: '马勇' },
  { id: 6, number: 207, phone: '18907626648', name: '孙秀兰' },
  { id: 7, number: 208, phone: '13588195590', name: '汤平' },
  { id: 8, number: 209, phone: '13527127111', name: '田霞' },
  { id: 9, number: 210, phone: '18903128598', name: '谭丽' },
  { id: 10, number: 211, phone: '13573015271', name: '胡霞' },
  { id: 11, number: 212, phone: '13544838889', name: '傅磊' },
  { id: 12, number: 213, phone: '18977822155', name: '罗明' },
  { id: 13, number: 214, phone: '13509142757', name: '叶军' },
  { id: 14, number: 215, phone: '13526684669', name: '林杰' },
  { id: 15, number: 216, phone: '13557358470', name: '萧磊' },
  { id: 16, number: 217, phone: '18988881414', name: '段娜' },
  { id: 17, number: 218, phone: '13228181051', name: '阎平' },
  { id: 18, number: 219, phone: '13506140478', name: '范霞' }
]
yaogengzhu commented 2 years ago

这个文章不错! 链接