mockjs学习

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')
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值