安裝
(1)npm install axios --save
(2)npm install mockjs --save-dev
(3)npm install json5 --save-dev (記得編輯器安裝json5插件)
// 1.vue.config.js
devServer: {
before: require('./src/mock/index.js'),
open: true,
host: 'xxxxxxxxx', ip地址
port: 8080,
hotOnly: true,
watchContentBase: true,
proxy: {
"/api": {
target: "http://xxxxxxxx:8080",
pathRewrite: {
"^/api": ""
}
}
}
}
// 2.mock文件夾
index.js
const fs = require('fs');
const path = require('path');
const Mock = require('mockjs');
const JSON5 = require('json5');
// 讀取json文件
function getJsonFile(filePath) {
let json = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8');
return JSON5.parse(json);
}
module.exports = function (app) {
if (process.env.MOCK == 'true') {
// 監(jiān)聽http請求
app.get('/user/userinfo', function (rep, res) {
// getJsonFile方法定義了讀取json文件
let json = getJsonFile('./userInfo.json5');
// 將json傳入Mock.mock方法中瓜喇,生成的數(shù)據(jù)返回瀏覽器
res.json(Mock.mock(json));
})
app.get('/user/goods', function (rep, res) {
// getJsonFile方法定義了讀取json文件
let json = getJsonFile('./goods.json5');
// 將json傳入Mock.mock方法中,生成的數(shù)據(jù)返回瀏覽器
res.json(Mock.mock(json));
})
}
}
userInfo.json5
{
id: "@id()",
username: "@cname()", // 隨機生成中文名
date: "@date()", // 隨機生成日期
avatar: "@image('200x200','red','#fff','avatar')", // 隨機生成圖片
description: "@paragraph()", // 隨機生成描述
ip: "@ip()", // 隨機IP
email: "@email()", // 郵件
"array|1-4": [
{
"id|+1": 1,
name: "@cname"
}
]
}
// 3.最外層目錄
.env.development
MOCK = true
// 4.組件中使用
getData() {
this.axios.get('/api/user/userinfo').then((result) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
}