Mock.js基本使用

核心

生成随机数据,拦截 Ajax 请求

安装

npm install mockjs

yarn add mockjs

语法规范

语法可参考官网API,前往语法规范;效果可参考官网示例,前往示例

方法

参数

rurl
可选
表示需要拦截的 URL,可以是 URL 字符串或 URL 正则。例如 //domain/list.json/、’/domian/list.json’。

rtype
可选
表示需要拦截的 Ajax 请求类型。例如 GET、POST、PUT、DELETE 等。

template
可选
表示数据模板,可以是对象或字符串。例如 { ‘data|1-10’:[{}] }、’@EMAIL’。

function(options)
可选
表示用于生成响应数据的函数。
options
指向本次请求的 Ajax 选项集,含有 url、type 和 body 三个属性。

Mock.mock( template )

根据数据模板生成模拟数据

var template = {
    'title': 'Syntax Demo',

    'string1|1-10': '★',
    'string2|3': 'value',

    'number1|+1': 100,
    'number2|1-100': 100,
    'number3|1-100.1-10': 1,
    'number4|123.1-10': 1,
    'number5|123.3': 1,
    'number6|123.10': 1.123,

    'boolean1|1': true,
    'boolean2|1-2': true,

    'object1|2-4': {
        '110000': '北京市',
        '120000': '天津市',
        '130000': '河北省',
        '140000': '山西省'
    },
    'object2|2': {
        '310000': '上海市',
        '320000': '江苏省',
        '330000': '浙江省',
        '340000': '安徽省'
    },

    'array1|1': ['AMD', 'CMD', 'KMD', 'UMD'],
    'array2|1-10': ['Mock.js'],
    'array3|3': ['Mock.js'],

    'function': function() {
        return this.title
    }
}
var data = Mock.mock(template)
$('<pre>').text(JSON.stringify(data, null, 4))
	.appendTo('body')

输出:

{
    "title": "Syntax Demo",
    "string1": "★★★★★★★★",
    "string2": "valuevaluevalue",
    "number1": 100,
    "number2": 41,
    "number3": 51.448,
    "number4": 123.0554812,
    "number5": 123.184,
    "number6": 123.1231337245,
    "boolean1": false,
    "boolean2": false,
    "object1": {
        "110000": "北京市",
        "120000": "天津市",
        "130000": "河北省",
        "140000": "山西省"
    },
    "object2": {
        "320000": "江苏省",
        "330000": "浙江省"
    },
    "array1": "AMD",
    "array2": [
        "Mock.js",
        "Mock.js",
        "Mock.js",
        "Mock.js",
        "Mock.js",
        "Mock.js",
        "Mock.js",
        "Mock.js",
        "Mock.js"
    ],
    "array3": [
        "Mock.js",
        "Mock.js",
        "Mock.js"
    ],
    "function": "Syntax Demo"
}

Mock.mock( rurl, template )

记录数据模板。当拦截到匹配 rurl 的 Ajax 请求时,将根据数据模板 template 生成模拟数据,并作为响应数据返回。

Mock.mock(/\.json/, {
    'list|1-10': [{
        'id|+1': 1,
        'email': '@EMAIL'
    }]
})
$.ajax({
    url: 'hello.json',
    dataType: 'json'
}).done(function(data, status, jqXHR){
    $('<pre>').text(JSON.stringify(data, null, 4))
    	.appendTo('body')
})

输出:

{
    "list": [
        {
            "id": 1,
            "email": "h.rxkzcx@bwiebswmj.sn"
        },
        {
            "id": 2,
            "email": "c.zibiggjtvc@klv.us"
        },
        {
            "id": 3,
            "email": "i.vffrm@wccc.tn"
        }
    ]
}

Mock.mock( rurl, function( options ) )

记录用于生成响应数据的函数。当拦截到匹配 rurl 的 Ajax 请求时,函数 function(options) 将被执行,并把执行结果作为响应数据返回。

Mock.mock(/\.json/, function(options) {
    return options
})
$.ajax({
    url: 'hello.json',
    dataType: 'json'
}).done(function(data, status, jqXHR) {
    $('<pre>').text(JSON.stringify(data, null, 4))
        .appendTo('body')
})
$.ajax({
    url: 'hello.json',
    dataType: 'json',
    data: {
        foo: 1,
        bar: 2,
        faz: 3
    }
}).done(function(data, status, jqXHR) {
    $('<pre>').text(JSON.stringify(data, null, 4))
        .appendTo('body')
})
$.ajax({
    url: 'hello.json',
    type: 'post',
    dataType: 'json',
    data: {
        foo: 1,
        bar: 2,
        faz: 3
    }
}).done(function(data, status, jqXHR) {
    $('<pre>').text(JSON.stringify(data, null, 4))
        .appendTo('body')
})

输出:

{
    "url": "hello.json",
    "type": "GET",
    "body": null
}
{
    "url": "hello.json",
    "type": "POST",
    "body": "foo=1&bar=2&faz=3"
}
{
    "url": "hello.json?foo=1&bar=2&faz=3",
    "type": "GET",
    "body": null
}

Mock.mock( rurl, rtype, template )

记录数据模板。当拦截到匹配 rurl 和 rtype 的 Ajax 请求时,将根据数据模板 template 生成模拟数据,并作为响应数据返回。

Mock.mock(/\.json/, 'get', {
    type: 'get'
})
Mock.mock(/\.json/, 'post', {
    type: 'post'
})

$.ajax({
    url: 'hello.json',
    type: 'get',
    dataType: 'json'
}).done(function (data, status, jqXHR) {
    $('<pre>').text(JSON.stringify(data, null, 4))
        .appendTo('body')
})

$.ajax({
    url: 'hello.json',
    type: 'post',
    dataType: 'json'
}).done(function (data, status, jqXHR) {
    $('<pre>').text(JSON.stringify(data, null, 4))
        .appendTo('body')
})

输出:

{
    "type": "get"
}
{
    "type": "post"
}

Mock.mock( rurl, rtype, function( options ) )

记录用于生成响应数据的函数。当拦截到匹配 rurl 和 rtype 的 Ajax 请求时,函数 function(options) 将被执行,并把执行结果作为响应数据返回。

Mock.mock(/\.json/, 'get', function(options) {
    return options.type
})
Mock.mock(/\.json/, 'post', function(options) {
    return options.type
})

$.ajax({
    url: 'hello.json',
    type: 'get',
    dataType: 'json'
}).done(function (data, status, jqXHR) {
    $('<pre>').text(JSON.stringify(data, null, 4))
        .appendTo('body')
})

$.ajax({
    url: 'hello.json',
    type: 'post',
    dataType: 'json'
}).done(function (data, status, jqXHR) {
    $('<pre>').text(JSON.stringify(data, null, 4))
        .appendTo('body')
})

输出:

"GET"
"POST"

实例

此项目使用vue + axios + mock,axios的使用可参考此文章
安装完mock包后,在 src 下新建mock文件夹,并在mock文件夹下新建 index.js
在这里插入图片描述
index.js 中添加mock示例:

// src/mock/index.js
const Mock = require('mockjs')

const data = Mock.mock({
  'list|10': [ // 生成10条数据 数组
    {
      'shopId|+1': 1, // 生成商品id,自增1
      'shopMsg': '@ctitle(10)', // 生成商品信息,长度为10个汉字
      'shopName': '@name', // 生成商品名,随机英文名
      'shopTel': /^1(5|3|7|8)[0-9]{9}$/, // 生成随机电话号
      'shopAddress': '@county(true)', // 随机生成地址
      'shopPrice|30-1000': 30, // 随机生成商品价格 在30-1000之间
      'shopLogo': "@Image('100x40','#c33', '#ffffff','随机图')" // 生成随机图片,大小/背景色/字体颜色/文字信息
    }
  ],
  'count': 10,
  'total': 100
})

// 三个参数。第一个路径,第二个请求方式post/get,第三个回调,返回值
Mock.mock(/api\/getSomething/, 'get', () => {
  return { code: 200, data, msg: '请求成功' }
})

main.js 中导入mock文件

import '@/mock'

src/api/index.js 中添加一条请求,请求地址要与上面mock拦截的地址一致(即api/getSomethind

// src/api/index.js
import request from '@/utils/request'

// 查询
export function getSomething() {
  return request({
    url: '/api/getSomething'
  })
}

在页面调用请求,即可获得返回的模拟数据

// Home.vue
<script>
import { getSomething } from '@/api'

export default {
  methods: {
    async _getSomething() {
      const res = await getSomething()
      console.log(res)
    }
  }
}
</script>

输出:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值