1. npm install -D mockjs
2. 在src文件下建文件夹,mock
3. mockMsg.js
const msgObj = {
'100': 'ok',
'101': 'Parameter error',
'104': ''
}
export default msgObj
4. mock/index.js
import mockMsg from './mockMsg.js'
const Mock = require('mockjs')
const requireServices = require.context('./service', false, /[a-zA-Z]\w+\.js/)
let mockServices = {}
requireServices.keys().forEach(fileName => {
const serviceConfig = requireServices(fileName)
const serviceName = fileName
.split('/')
.pop()
.replace(/\.\w+$/, '')
mockServices[serviceName] = serviceConfig.default || serviceConfig
})
export default {
install() {
Object.keys(mockServices).forEach(serviceName => {
let mockService = mockServices[serviceName]
Object.keys(mockService).forEach(api => {
let url = '/' + serviceName + '/' + api
let result = mockService[api](Mock)
Mock.mock(url, result.type || 'get', function() {
return {
code: result.code,
msg: mockMsg[result.code],
data: result.data
}
})
})
})
}
}
5. mock/service/user.js
const userInfoDefault = [
{ name: 'fff', account: 'f333' },
{ name: 'ggg', account: 'g111' }
]
const userInfo = localStorage.userInfo || userInfoDefault
export default {
getUserInfo() {
return {
code: '100',
data: userInfo
}
},
queryUser(param) {
const certainUser =
param &&
userInfo.find((user) => {
return Object.keys(user).some((key) => {
return user[key].includes(param)
})
})
return {
type: 'post',
code: param ? '100' : '101',
data: certainUser || []
}
}
}