1. 安装插件
npm i -D mockjs
npm i -D json5
2. 在根目录下新建Mock文件夹,并新建index.js、test.json5
mkdir Mock
touch index.js test.json5
// index.js
const Mock = require('mockjs')
const path = require('path')
const fs = require('fs')
const json5 = require('json5')
const getJsonFile = (filepath)=>{
const data = fs.readFileSync(path.resolve(__dirname,filepath),'utf-8')
return json5.parse(data)
}
const json = getJsonFile('./test.json5')
// express
const API = (app) => {
if(process.env.MOCK === 'true') {
// req 表示的请求 res表示的响应
app.get('/mock/test', (req, res) => {
const data = Mock.mock(json)
// res.send res.json
res.json(data)
})
}
}
module.exports = API
// test.json5
{
'list|1-10': [{
'id|+1': 1,
'createTime': "@datetime('yyyy-MM-dd HH:mm:ss')",
'chinese': '@cword(3)',
'english': '@word()',
'phonetic': '@word()',
'example': '@sentence()',
}]
}
3. 修改vue.config.js
module.exports = {
devServer:{
// 拦截器
before:require('./mock')
}
}
4. api文件新增函数
// 测试Mock
export function testMock() {
return axios({
method: 'get',
url: '/mock/test',
})
}
5. 组件内使用
testMock().then((res) => {
console.log(res)
const {list} = res?.data;
this.list = [...list];
this.total = this.list.length;
})