1.安裝依賴(lài)
# 使用axios發(fā)送ajax
cnpm install axios --save
# 使用mockjs產(chǎn)生隨機(jī)數(shù)據(jù)
cnpm install mockjs --save-dev
# 使用json5解決json文件,無(wú)法添加注釋問(wèn)題
cnpm install json5 --save-dev
2.新建mock文件夾 index.js文件
- 在index.js中配置
const fs = require("fs");
const path = require("path");
const Mock = require("mockjs"); //mockjs 導(dǎo)入依賴(lài)模塊
const JSON5 = require("json5"); //json5的作用是可以解析json文件中的注釋
//讀取json文件
function getJsonFile(filePath) {
//讀取指定json文件
var json = fs.readFileSync(path.resolve(__dirname, filePath), "utf-8");
//解析并返回
return JSON5.parse(json);
}
//返回一個(gè)函數(shù)
module.exports = function ({app}) {
if (process.env.MOCK == "true") {
//為了滿(mǎn)足當(dāng)后臺(tái)有接口的時(shí)候瓤狐,不是使用mock數(shù)據(jù)剩膘,在此處做一個(gè)判斷铺董,可以在.env文件中對(duì)設(shè)置
//監(jiān)聽(tīng)http請(qǐng)求
app.get("/user/userinfo", function (rep, res) {
//每次響應(yīng)請(qǐng)求時(shí)讀取mock data的json文件
//getJsonFile方法定義了如何讀取json文件并解析成數(shù)據(jù)對(duì)象
var json = getJsonFile("./userInfo.json5");
//將json傳入 Mock.mock 方法中房交,生成的數(shù)據(jù)返回給瀏覽器
console.log(app);
res.json(Mock.mock(json));
});
}
};
3. mock文件夾下新建json5文件
{
"id": "@id()",// 得到隨機(jī)的id值
"username":"@cname()",// 生成隨機(jī)的中文名字
"date": "@date()", // 生成隨機(jī)的日期
"avatar": "@image('900x200','red','#000','你好啊')",// 生成隨機(jī)的圖片,參數(shù):size,background,foreground,text
"text": "@cword(1,3)",// 隨機(jī)的描述信息
"ip": "@ip()",// 隨機(jī)的id地址
"email": "@email()"http:// 隨機(jī)的email地址
}
4.配置vue.config.js文件
module.exports = ({
lintOnSave:false,
devServer: {
// before 表示在devServer中的配置先經(jīng)過(guò)before的操作
onBeforeSetupMiddleware: require("./mock") // 引入mock.js
}
})
5.在vue文件中發(fā)送請(qǐng)求
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
};
},
beforeMount() {
console.log(111)
axios
.get("/user/userinfo")
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
},
};
</script>
6.、當(dāng)項(xiàng)目中接口給到我么們時(shí),我們移除mock的方法
- 根文件下新建 .env.development文件
MOCK=true;
在env文件中两蟀,進(jìn)行配置。因?yàn)樵趍ock.js文件中震缭,我們已經(jīng)設(shè)置了監(jiān)聽(tīng)赂毯,并進(jìn)行了判斷,所以此處MOCK如果為false,就不會(huì)執(zhí)行mock中的內(nèi)容拣宰。