mockjs的作用
- 生成模拟数据
- 模拟 Ajax 请求,返回模拟数据
- 基于 HTML 模板生成模拟数据(后续更新)
- 帮助编写单元测试(后续更新)
Vue 中使用 mock
- 有两种使用方式,一种是仅编写数据来调用,第二种是编写 服务+数据模拟真实接口(可在network查看)
- Mock对象API用例查看(推荐只看这个就可以)
- 官方mock定义api查询
第一种方式,编写mock
- 可以写完整action url:http://localhost/login
- 同一域下,也可以只写api形式:/login
- 使用 Mock.mock 可以编写多个接口数据
import Mock from 'mockjs'; //es6语法引入mock模块
Mock.mock('/login', { //输出数据
'name': '@name', //随机生成姓名
//还可以自定义其他数据
});
Mock.mock('/list', { //输出数据
'age|10-20': 10
//还可以自定义其他数据
});
两种数据调用方式
1.使用 Mock.mock 直接编写
Mock.mock('@date("yyyy-MM-dd")');//"1984-06-12"
2.使用 随机函数 Random 编写
var Random = Mock.Random;
Random.date('yyyy-MM-dd');//"2018-08-16"
第一种方式,调用mock
- 注意,将 mock.js 直接导入即可
import "../mock/mock.js";
axios.post("/login").then(response => {
if (response.data) {
this.jumpToKpi();
}
});
第二种方式,编写server
使用 express 提供服务
- 首先需要安装几个依赖:express、babel-cli(支持es6编写服务)
- 通过 babel-node mockservice.js 命令启动服务
- 注意,babel-node命令不能支持 import 写法,使用 require 即可。如要用 import 请自行解决
npm i --save-dev express
npm install --save-dev babel-cli
babel-node mockservice.js
跨域设置
- 假设 express 服务使用 8090 端口,而 vue 开发一般启动 8080,则必定跨域,需在 server 端进行设置
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
在chrome network下可查看到接口调用
//请求接口地址
http://localhost:8090/list
//数据返回
{
"status":200,
"list":[
{
"name":"John Brown",
"age":50,
"address":"东北",
"date":"2017-08-17"
},
{
"name":"Jim Green",
"age":25,
"address":"东北",
"date":"2017-08-17"
},
{
"name":"Joe Black",
"age":35,
"address":"东北",
"date":"2017-08-17"
}
]
}
完整的 mockservice.js 如下
// import express from "express"
// import Mock from "mockjs"
const express = require('express'); //引入express
const Mock = require('mockjs'); //引入mock
let app = express();
const Random = Mock.Random;
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.use('/list', function (req, res) {
res.json(Mock.mock({
'status': 200,
'list|10': [
{
"name|+1": ["John Brown", "Jim Green", "Joe Black", "Jon Snow"],
"age|18-70": 70,
"address": Random.region(),
"date": Random.date()
}
]
}))
})
app.listen('8090', () => {
console.log('监听端口 8090')
})
第二种方式,编写mock
- 同第一种方式
Mock对象API用例查看
- String类
- Number类
- Boolean类
- ==Object类==
- ==Array类==
- Function类
- RegExp类(略)
- Path类(略)
- ==Basic类 and Random==
- ==Date类==
- Image类
- Color类
- ==Text类==
- Name类
- ==Web类==
- ==Address类==
- Helper类
- Miscellaneous类
/* String类 */
var str = Mock.mock({
"name|1-10":"zk",//1-10次重复
"home|3":"china",//3次重复
})
console.log(str);
//{ "name": "zkzkzkzkzk", "home": "chinachinachina" }
/* Number类 */
var num = Mock.mock({
"age":22,
"int|1-100":100,//1-100随机
"floor1|1-100.1-5":1,//整数部分1-100,小数1-5位
"floor2|23.1-3":1,//整数23,小数1-3位
"floor3|123.3":1//整数123,小数3位
})
console.log(num);
//{ "age": 22, "int": 50, "floor1": 11.8427, "floor2": 23.6, "floor3": 123.512 }
/* Boolean类 */
var bool = Mock.mock({
"can":true,//布尔值,true
"has|1":true,//布尔值,可真可假
"is|1-2":true,//布尔值,可真可假
})
console.log(bool);
//{ "can": true, "has": true, "is": false }
/* Object类 */
var obj = Mock.mock({
//从散列表中,随机取出2个值
"object1|2": {
"310000": "上海市",
"320000": "江苏省",
"330000": "浙江省",
"340000": "安徽省"
},
//从散列表中,随机取出1-3个值
"object2|1-3": {
"310000": "上海市",
"320000": "江苏省",
"330000": "浙江省",
"340000": "安徽省"
}
})
console.log(obj);
//{ "object1": { "310000": "上海市", "330000": "浙江省" }, "object2": { "310000": "上海市", "320000": "江苏省", "330000": "浙江省" } }
/* Array类 */
var arr = Mock.mock({
//随机取1个数
"arr1|1":[1,2,3,4,5,6,7],
//按序生成一个list
"arr2|4":[{
"name|+1":["gs","zk","lili"]
}],
//生成一个1-4个项的数组
"arr3|1-4":["green"]
})
console.log(arr);
//{ "arr1": 3, "arr2": [ { "name": "gs" }, { "name": "zk" }, { "name": "lili" }, { "name": "gs" } ], "arr3": [ "green", "green", "green", "green" ] }
/* Function类 */
var fun = Mock.mock({
"fun1":"this is fun1",
"fun2":function(){
return this.fun1
}
})
console.log(fun);
//{ "fun1": "this is fun1", "fun2": "this is fun1" }
/* RegExp类(略) */
/* Path类(略) */
/* Basic类 and Random */
var Random = Mock.Random;
// Random.boolean();
var random = {
bool1: Mock.mock('@boolean'),//
natural1: Random.natural(60, 100),
integer1:Random.integer(60, 100),
float1:Random.float(10,20,3,5),//浮点数,限制小数位最小3位,最大5位
}
console.log(random);
//{ "bool1": false, "natural1": 79, "integer1": 85, "float1": 16.5758 }
//Random.range(start?, stop, step?)
var range = {
range1:Random.range(10),
range2:Random.range(3,8),//3-8但不包含8
}
console.log(range);
//{ "range1": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], "range2": [ 3, 4, 5, 6, 7 ] }
/* Date类 */
//Random.date
var date = {
date:Random.date(),
date1:Random.date('yyyy-MM-dd'),
date2:Random.date('yy-MM-dd'),
date3:Random.date('y-MM-dd'),
date4:Random.date('y-M-d'),
}
console.log(date);
//{ "date": "2015-04-30", "date1": "2013-01-07", "date2": "97-04-02", "date3": "03-10-04", "date4": "83-1-8" }
//Random.time
console.log(Random.time());
//20:21:26
//Random.datetime
var datetime = {
datetime1:Random.datetime('yyyy-MM-dd A HH:mm:ss'),
datetime2:Random.datetime('yy-MM-dd a HH:mm:ss'),
datetime3:Random.datetime('y-MM-dd HH:mm:ss'),
datetime4:Random.datetime('y-M-d H:m:s'),
}
console.log(datetime);
//{ "datetime1": "1981-03-27 AM 10:47:11", "datetime2": "86-03-16 am 06:25:02", "datetime3": "02-12-18 18:13:46", "datetime4": "84-6-6 1:20:37" }
//Random.now
console.log(Random.now());
//2019-02-11 11:10:22
/* Image类 */
//Random.image
var image = {
image1:Random.image(),
image2:Random.image('200x100'),
image3:Random.image('200x100', '#FF6600'),
image4:Random.image('200x100', '#4A7BF7', 'Hello'),
}
console.log(image);
//{ "image1": "http://dummyimage.com/234x60", "image2": "http://dummyimage.com/200x100", "image3": "http://dummyimage.com/200x100/FF6600", "image4": "http://dummyimage.com/200x100/4A7BF7&text=Hello" }
//Random.dataImage
Random.dataImage('200x100', 'Hello Mock.js!');//生成base64图片的代码
/* Color */
//Random.color()
console.log(Random.color());
//Random.rgb()
console.log(Random.rgb());
//Random.rgba()
console.log(Random.rgba());
/* Text类 */
//paragraph
var paragraph = {
paragraph1:Random.paragraph(2),
paragraph2:Random.paragraph(1,4),//生成1-4段落的文本
}
console.log(paragraph);
//{ "paragraph1": "Rwolb iow nzw tncvxbjo xcuwxztvp sluowwdbbe ebspm qxhu oyihkjgo cyperf keizgr wcyk kgsdlxk fkt tlwr fwoappj pcfoln. Wxl gqb tlayp fst ylpikqzvjl ywiwudcu jjhc ikuiojcxdv herlliuti yrebxci mhbwxy rmfyw.", "paragraph2": "Ecifwwsor msyhxovy gdgrr nxpg wfkd suveigx gxtdqvydy oncubsadx cujix qtpkixn tbkzwuf suiobevg qstrs. Mgkxu ugvjz hjxw oje bfwlfmu rgvwqg uee mbub wnjn msjccuihk quprpmwuxy cmbg. Sem mexgend dlijdlo mqooaorr uimveu ktst kbusaeo ntjwbba hftkjq lmbfjklkqc dakew jxidcsr byfqwfj yye." }
//cparagraph | 中文段落
var cparagraph = {
cparagraph1:Random.cparagraph(2),
cparagraph2:Random.cparagraph(1,4),//生成1-4段落的[中文文本]
}
console.log(cparagraph);
//{ "cparagraph1": "为必子之有院场走九府江制受。或全亲书以众与改你步积利江争采。", "cparagraph2": "小特区战高系应化次主它人系者。发全七第历东道装号己育结界满铁整习算。" }
//sentence
var sentence = {
sentence1:Random.sentence(5),//生成5个单词的句子
sentence2:Random.sentence(1,10)
}
console.log(sentence);
//{ "sentence1": "Kmuu apvtblwsk pyqleysce xoghbiiymp mxhkmogvgu.", "sentence2": "Utdnre vbmc bziw monmkuz pkwjp qthrjwjq hwbgjwfqk wvdfw jybjjgv." }
//csentence | 中文句子
var csentence = {
csentence1:Random.csentence(5),//生成5个单词的句子
csentence2:Random.csentence(1,10)
}
console.log(csentence);
//{ "csentence1": "习定千机布。", "csentence2": "去斗或己。" }
//word
var word = {
word1:Random.word(5),//生成单词
word2:Random.word(1,10)
}
console.log(word);
//{ "word1": "ywwxr", "word2": "chkawikz" }
//cword | 中文单词
var cword = {
cword1:Random.cword(5),//生成单词
cword2:Random.cword(1,10),
cword3:Random.cword('零一二三四五六七八九十', 3)
}
console.log(cword);
//{ "cword1": "下标力从划", "cword2": "山许切往理也天家革", "cword3": "九十二" }
//title
var title = {
title1:Random.title(5),//生成单词
title2:Random.title(1,10)
}
console.log(title);
//{ "title1": "Trkfpfrct Vfhgwer Kejisbvjws Epfounrun Vwra", "title2": "Stns Hcfppzc" }
//ctitle | 中文标题
var ctitle = {
ctitle1:Random.ctitle(5),//生成单词
ctitle2:Random.ctitle(1,10)
}
console.log(ctitle);
/* Name类 */
//Random.first()
//Random.last()
//Random.name()
var cname = {
cfirst:Random.cfirst(),//只能是一个字
clast:Random.clast(),//只能是一个字
cname:Random.cname(),//默认为2个字,可以设为3个字,4个字不行
}
console.log(cname);
//{ "cfirst": "段", "clast": "伟", "cname": "蔡刚" }
/* Web类 */
//Random.url()
console.log(Random.url());//注意,会有各种协议头,不只http
//rlogin://eertsd.uy/ihthk
//Random.domain()
console.log(Random.domain());//注意,会有奇葩域名
//lywxjl.tel
//Random.protocol()
console.log(Random.protocol());//注意,会有ftp协义等等
//ftp
//Random.email()
console.log(Random.email());
//o.gyu@jox.mz
//Random.ip()
console.log(Random.ip());
//13.224.127.79
/* Address类 */
//Random.region() | 地域大区
console.log(Random.region());
//东北
//Random.province() | 省
console.log(Random.province());
//河南省
//Random.city() | 城市
console.log(Random.city());
console.log(Random.city(true));//增加参数后,会提供城市所在的省
//大同市
//江苏省 常州市
//Random.county() | 区县
console.log(Random.county());
console.log(Random.county(true));//增加参数后,会提供区县所属的市和省
//青山区
//四川省 德阳市 中江县
/* Helper类 */
//Random.capitalize() | 首字母大写
console.log(Random.capitalize('hello'));
//Hello
//Random.upper() | 大写
console.log(Random.upper('hello'));
//HELLO
//Random.lower() | 小写
console.log(Random.lower('HELLO'));
//hello
//Random.pick() | 随机抽取
console.log(Random.pick(['a', 'e', 'i', 'o', 'u']));
//i
//Random.shuffle() | 洗牌
console.log(Random.shuffle(['a', 'e', 'i', 'o', 'u']));
//[ "o", "i", "u", "e", "a" ]
/* Miscellaneous | 混杂类 */
//Random.guid() | 全局唯一标识符
console.log(Random.guid());
//7AAEc148-FcAD-7EBA-0dAD-f7ac1c43AdCC
//Random.id()
console.log(Random.id());
//710000198410172520
//Random.increment | 自增
console.log(Random.increment());//1
console.log(Random.increment());//2
console.log(Random.increment());//3
console.log(Random.increment(100));//103
console.log(Random.increment());//104
console.log("");
console.log("");
console.log("");
console.log("");
console.log("");