vue中如何使用mockjs摸拟接口的各种数据
程序员文章站
2023-02-21 09:02:42
mock有两种使用方式,一种是仅编写数据来调用,第二种是编写 服务+数据模拟真实接口(可在network查看) ......
mockjs的作用
- 生成模拟数据
- 模拟 ajax 请求,返回模拟数据
- 基于 html 模板生成模拟数据(后续更新)
- 帮助编写单元测试(后续更新)
vue 中使用 mock
- 有两种使用方式,一种是仅编写数据来调用,第二种是编写 服务+数据模拟真实接口(可在network查看)
- 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("");
上一篇: 正方形(类型:枚举、一级、C++)