由于后端数据接口可能没有编写好,由于目前基本都是前后端分离开发,前端和后端并行同时开发,可以通过mock数据来解决后端接口没有写好的问题
mock数据之前,通常前端要和后端沟通数据接口结构和数据类型
data.json
{
"code": 200,
"data": [
{
"id": 1111,
"name": "xxx"
},
{}
],
"msg": "成功"
}
mock.js
mock.js官方仓库,看这里
非官方mock规则示例,看这里
mockjs数据模拟规则:
Mock.mock({
code:200,
"data|10":[
{ //数字递增
"id|+1":400,
//模拟中文姓名
"teacher_name":"@cname",
//中文句子@csentence 中文标题 @ctitle 中文段落:@cparagraph
title:'@csentence',
"created_at|+5":1634524521,
//从数组中随机挑出一个状态
"jump_type|1":[0,1,2],
"status|1":[200,404,500],
//模拟图片 @image('图片尺寸','颜色','文本')
"banner_img":"@image('200x100','#00f','2109A')",
//模拟省、市、县
"address":"@county(true)",
//模拟网址
"url":"@url",
//模拟ip地址
"reg_ip":"@ip"
}
],
msg:'success'
})
npm i mockjs
//引入mockjs
import Mock from "mockjs";
//生成mock数据
const teahcerMock = Mock.mock({
code: 200,
"data|10": [
{
//数字递增 或通过@id生成长数字 235235253235
"id|+1": 400,
//模拟中文姓名
teacher_name: "@cname",
//中文句子@csentence 中文标题 @ctitle 中文段落:@cparagraph
title: "@csentence",
"created_at|+5": 1634524521,
//从数组中随机挑出一个状态
"jump_type|1": [0, 1, 2],
"status|1": [200, 404, 500],
//模拟图片 @image('图片尺寸','颜色','文本')
banner_img: "@image('200x100','#00f','2109A')",
//模拟省、市、县
address: "@county(true)",
//模拟网址
url: "@url",
//模拟ip地址
reg_ip: "@ip",
},
],
msg: "success",
});
//抛出数据
export default teahcerMock;
index.js
import Mock from "mockjs";
//引入老师的mock数据
import TeacherMock from "./teahcer_data";
//生成请求的url,为了axios请求用的
//Mock.mock(请求地址,请求方式,请求的数据)
Mock.mock("http://www.2109A.com/api/teahcers", "get", TeacherMock);
main.js引入依赖
//引入mock
import "@/mock";
使用axios请求mock数据
//请求mock数据
const getTeachFn = () => {
axios.post("http://www.2109A.com/api/teahcers").then((res) => {
console.log("能否拿到:", res);
});
};
HTML:
<button @click="getTeachFn">请求mock数据</button>
线上mock平台,看这里
线上模拟界面:
也支持请求参数判断处理:
{
"code": "0000",
"data": {
"verifySuccess": function({_req, Mock}) {
let body = _req.body;
return body.username === 'admin' && body.password === '123456';
},
"userInfo": function({_req, Mock}) {
let body = _req.body;
if (body.username === 'admin' && body.password === '123456') {
return Mock.mock({
username: "admin",
email: "@email",
address: "@address"
});
} else {
return null;
}
},
},
"desc": "成功"
}