项目结构:
-mock //模拟数据存放目录
-Demo.js //模拟数据文件
-public //静态文件存放目录
-shell //脚本存放目录
-src //源码存放目录
-package.json //不解释
-vue.config.js //vue 配置文件
-proxy.config.js //模拟数据加载逻辑
Demo.js 内容:
'use strict';
var Mock = require('mockjs')
var Random = Mock.Random;
module.exports = {
'GET /api/demo/test' : function (req,res,next) {
//返回固定格式数据
var data = [
{
"id": 1,
"name": '111',
"gender": '男'
}
];
setTimeout(function () {
res.json(data);
}, 500);
},
'GET /api/demo/queryPage': function (req, res, next) {
//返回模拟数据
var data = Mock.mock({
"content|10": [{
branch_id: "@integer(1,10)",
member_name: "@cname",
member_no: "@word(5,10)",
card_no: "@word(5,10)",
}],
"number": '@integer(100,200)',
"size": 10,
"totalElements": 500,
});
setTimeout(function () {
res.json(data);
}, 500);
},
}
proxy.config.js 内容:
'use strict';
const mock = {};
var fs = require('fs');
var path = require('path');
function forEachFile(file) {
//这里考虑到如果判断目录,会走异步代码,会导致导出的数据为空,所以做了一个蹩脚的判断
if(file.indexOf(".js") != -1){
console.log(file);
Object.assign(mock, require('.' + file));
}else {
fs.readdirSync(path.join(__dirname + file)).forEach(function (subFile) {
forEachFile(file + "/" + subFile);
});
}
}
//加载mock目录下所有的js文件
forEachFile("/mock");
module.exports = mock;
package.json 增加代理:
devServer: {
proxy: {
'/': {
target: 'http://localhost:8000/',//前端模拟数据,默认端口8000
ws: false,
changeOrigin: true,
secure: false
}
}
},
操作步骤
1. npm install puer -D //安装puer
2. npm install mockjs -D //安装mockjs
3. package.json 增加 scripts
"mock": "puer --no-launch -r proxy.config.js",
4. 启动mock
npm run mock
5. 启动项目
npm run serve
6. 地址栏直接访问mock http://localhost:8000/api/demo/queryPage
7. axios 通过代码访问api ,我这里不赘述
网友评论