其他分享
首页 > 其他分享> > Mock.js自定义Mock

Mock.js自定义Mock

作者:互联网

https://github.com/nuysoft/Mock/wiki/Mock.Random
官方给的示例,为Mock.Random扩展方法,在数据模板中通过@扩展方法引用:

Random.extend({
    constellation: function(date) {
        var constellations = ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座']
        return this.pick(constellations)
    }
})
Random.constellation()
// => "水瓶座"
Mock.mock('@CONSTELLATION')
// => "天蝎座"
Mock.mock({
    constellation: '@CONSTELLATION'
})
// => { constellation: "射手座" }

比如生成电话号码:

const { Random } = require('mockjs')
var Mock = require('mockjs')
Random.extend({
    phonenumber: function(string){
       var prefixs = new Array("139","138","137","136","135","134","159","158","157","150","151","152","188","187","182","183","184","178","130","131","132","156","155","186","185","176","133","153","189","180","181","177")
       var phone = prefixs[parseInt(Math.random()*prefixs.length)]
       for (var i = 0; i < 8; i ++){
           phone = phone + Math.floor(Math.random()*10)
       }
       return phone

    }
})

//var phone = Mock.mock('@phonenumber')
console.log(Random.phonenumber())
console.log(Mock.mock('@phonenumber'))

标签:自定义,Random,js,phone,phonenumber,var,constellation,Mock
来源: https://www.cnblogs.com/shanzefenglai/p/15784596.html