# 前言
首先我们搞清啥叫 Mock
,英文翻译 Mock
是虚假的,虚设的
从技术层面来讲,就是虚假数据
那怎么解释 Mock
比较好呢,即 生成随机数据,拦截 Ajax 请求
(官网)。
# 使用
- 安装
npm install mockjs --save
- 应用
在项目根目录创建文件夹mock
,并创建文件index
,内容如下:
const Mock = require('mockjs');
module.exports = function (app) {
// 拦截的接口是 /user/getList
// 拦截后返回的模拟数据是 "{'name':'12345678'}"
app.get('/user/getList', function (req, res) {
res.json("{'name':'12345678'}");
})
}
- 在 vue.config.js 文件配置
devServer: {
before: require('./mock/index.js')
}
- 页面发送请求
import axios from 'axios'
export default{
mounted(){
axios.get('/user/getList').then(res=>{
console.log(res); // => "{'name':'12345678'}"
})
}
}
- 如后台已有接口,则把
第二步
加变量判断下就好,如下:
const Mock = require('mockjs');
module.exports = function (app) {
// 拦截的接口是 /user/getList
// 拦截后返回的模拟数据是 "{'name':'12345678'}"
if(process.env.mock){
app.get('/user/getList', function (req, res) {
res.json("{'name':'12345678'}");
})
}
}
好了,到此简单的应用就实现了(可能会用到的json5
),赶紧试试吧~~
网友评论