mock有兩種使用方式,一種是僅編寫數據來調用,第二種是編寫 服務+數據模擬真實介面(可在network查看) ...
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());
//[email protected]
//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("");