http://mockjs.com/
示例
http://mockjs.com/examples.html
文档
https://github.com/nuysoft/Mock/wiki
生成随机数据
export const user = Mock.mock({
'users|5': [ {
'name': '@cname', //中文名称
'age|1-100': 100, //100以内随机整数
'birthday': '@date("yyyy-MM-dd")', //日期
'city': '@city(true)' //中国城市
}]
})
拦截请求
简单使用
import axios from 'axios'
import Mock from 'mockjs'
created() {
Mock.mock(/\/user/, 'get', {
'users|5': [ {
'name': '@cname', //中文名称
'age|1-100': 100, //100以内随机整数
'birthday': '@date("yyyy-MM-dd")', //日期
'city': '@city(true)' //中国城市
}]
})
axios({
url: '/user',
method: 'get'
}).then(res => {
console.log(res)
})
}
在请求前添加mock 匹配上url 会被拦截
有type 匹配url + type
简单封装
1 mock/index.js
import Mock from 'mockjs'
// 占位符扩展
const Random = Mock.Random
Random.extend({
constellation: function(date) {
const constellations = ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座']
return this.pick(constellations)
},
region: function() {
const regions = ['华北地区', '华南地区', '华中地区', '华东地区', '西北地区', '西南地区', '东北地区']
return Random.pick(regions)
}
})
function registerModule(module, isOpen) {
if (isOpen) {
for (const key in module) {
((option) => {
if (option.isOpen !== false) {
Mock.mock(new RegExp(option.url), option.type, (opts) => {
// console.log(opts)
// console.log('\n')
// console.log('%cmock拦截, 请求: ', 'color: blue', opts)
// console.log('%cmock拦截, 响应: ', 'color:blue', option.data)
return Mock.mock(option.data)
})
}
})(module[key]() || {})
}
}
}
import * as user from './user'
import * as dataBoard from './databoard'
registerModule(user, true)
registerModule(dataBoard, true)
2 mock/user.js
export function getUserInfo() {
return {
url: '/user',
type: 'get',
data: {
msg: 'success',
code: 0,
data: {
'id': '@increment',
'name': '@cname',
'email': '@email',
'region': '@region',
'constellation': '@constellation',
'age|10-20': 12
}
}
}
}
使用
3 main.js
if (process.env.NODE_ENV === 'development') {
require('../mock/index')
}