什么是mockjs?他的使用场景是什么?
当前端工程师需要独立于后端并行开发时,后端接口还没有完成,那么前端怎么获取数据?
这时可以考虑前端搭建web server自己模拟假数据,mockjs用来生成随机数据,拦截 Ajax 请求。
下面引用mockjs官网的图片:
正文:如何改造vue-cli,将mockjs嵌入到webpack?
vue项目初始化
安装vue-cli脚手架工具,并初始化项目
//全局安装 vue-cli
npm install vue-cli -g
//创建一个基于vue-cli 模新项目
vue ui 。。。 这里就不多说了
安装依赖
//我们使用axios来发起http请求
npm install axios --save
//安装依赖mockjs
npm install mockjs --save-dev
在项目根路径下创建mock文件夹,并创建图片中mock文件夹中的几个文件
index.js 文件
const mock = require('mockjs')
const utils = require('./utils');//自定义工具模块
//返回一个函数
module.exports = function(app){
//监听http请求
app.get('/get/user', function (rep, res) {
//每次响应请求时读取mock data的json文件
//util.getJsonFile方法定义了如何读取json文件并解析成数据对象
try {
var json = utils.getJons('./user.json');
//将json传入 Mock.mock 方法中,生成的数据返回给浏览器
let user = {}
// 请求参数
const params = rep.query
for (const i of json) {
if(i.data.username == params.username) {
user = i
break ;
}
}
console.log('next', rep.query)
res.json(mock.mock(user));
} catch (e) {
console.log(e)
}
});
}
util.js 文件
const fs = require('fs')
const path = require('path')
module.exports = {
getJons :function (filePath) {
console.log(path.resolve(__dirname, filePath, 'utf-8'))
const res = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8')
return JSON.parse(res)
},
//读取json文件
getJsonFile:function (filePath) {
//读取指定json文件
var json = fs.readFileSync(path.resolve(__dirname,filePath), 'utf-8');
//解析并返回
return JSON.parse(json);
}
}
userInfo.json 文件
[
{
"error":500,
"data":{
"userid": "111",
"username": "test",
"date": "2222.12.29"
}
}
]
在路径build/webpack.dev.conf.js文件中的devServer属性中新添加一个before钩子函数,用来监听来自web的http请求。(关于devServer.before如何使用)
const devServerPort = 9527 // TODO: get this variable from setting.ts
module.exports = {
devServer: {
port: devServerPort,
open: true,
overlay: {
warnings: false,
errors: true
},
progress: false,
before: require('./mock'),//引入mock/index.js
}
}
浏览器发起请求,获取mock data
在App.vue文件中使用axios发起http请求
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png" />
<HelloWorld msg="Welcome to Your Vue.js App" />
{{username}}
</div>
</template>
<script>
// @ is an alias to /src
import axios from 'axios';
import HelloWorld from "@/components/HelloWorld.vue";
export default {
name: "Home",
components: {
HelloWorld
},
data() {
return {
username: ''
}
},
created() {
axios('/get/user', { params: {username: 'test'} }).then(res => {
console.log(res);
this.username = res.username;
})
}
};
</script>