安装相关依赖
yarn add axios -S
yarn add mockjs -D
yarn add json5 -D
测试Mockjs
新建mock文件夹,新建testMock.js文件
const Mock = require('mockjs')
let obj = Mock.mock({
id: '@id()',
username: '@cname()',
date: '@date()',
avatar: "@image('200x200','#50B347','#fff','avatar')",
desc: '@paragraph()',
ip: '@ip()',
email: '@email()',
})
console.log(obj)
json文件中如果说存在注释文件和编辑器都会报错,我们采用json5格式来让json格式可以存在注释
安装JSON5 syntax插件
引入JSON5库来解析JSON5格式
在mock文件夹下,新建testJSON5.js
const fs = require('fs')
const path = require('path')
const JSON5 = require('json5')
var json = fs.readFileSync(path.join(__dirname, './userInfo.json5'), 'utf-8')
var obj = JSON5.parse(json)
console.log(obj)
Mock与Vue-cli结合
是否开启Mock
在项目根路径新建.env.development文件
MOCK = true // 如果有后台接口了就改为false
在mock文件夹下,新建index.js
const fs = require('fs')
const path = require('path')
const Mock = require('mockjs')
const JSON5 = require('json5')
function getJsonFile(filePath) {
var json = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8')
return JSON5.parse(json)
}
module.exports = function (devServer) {
if (process.env.Mock == 'true') {
devServer.app.get('/user/userInfo', function (rep, res) {
var json = getJsonFile('./userInfo.json5')
res.json(Mock.mock(json))
})
}
}
在vue.config.js配置(不同版本配置写法不一样)
Vue中使用Mock,解决因webpack高版本出现的vue.config.js配置问题:options has an unknown property ‘before‘._liuyi008的博客-CSDN博客_mockjs vue webpack
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
onBeforeSetupMiddleware: require('./src/mock/index.js')
}
})
发起axios请求
<script>
import axios from 'axios'
export default {
name: 'App',
mounted() {
axios.get('/user/userInfo').then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}
}
</script>
Mock.js具体使用语法:
Mock.js
|