Mock在Vue项目中的应用(已封装好)

1.Mock介绍

生成随机数据,拦截 Ajax 请求
不需要修改既有代码,就可以拦截 Ajax 请求,返回模拟的响应数据。

这是Mock官网给出的介绍,简单明了的说出了Mock实现的主要功能,也告诉了我们Mock的主要应用场景就是前后端分离开发,前端在没有后台接口的情况下,自己拦截Ajax请求并返回自己造的数据以方便页面调试。

2.Mock的使用

第一步:安装mockjs

npm install mockjs

第二步 在项目中引入mockjs

项目目录下新建一个mock的文件夹,将下面几个文件复制进去
文件内容会在文章最后边

index.js
table.js
utils.js

第三步 配置Ajax请求的拦截

首先在main.js中加入

// mock拦截http请求
const { mockXHR } = require('../mock')
mockXHR()

if (process.env.NODE_ENV === 'development') {
  const { mockXHR } = require('../mock')
  mockXHR()
}

下面这个根据自身项目情况配置

然后配置mock拦截的请求接口 在table.js文件中url通过参数进行调整

url: '/api/dome',

在这样配置之后请求/api/dome接口就会被mock拦截了,至于需要返回的数据格式,就需要自己来设置了

3.Mock造数据

对于Mock来说造数据还是比较简单的
首先我们模拟后端接口返回长度 0-10 的对象数组

const data = Mock.mock({
  'items|0-10': [{
  }]
})

接下来我们可以给这个对象数组添加数据 如:

const data = Mock.mock({
  'items|0-10': [{
    'ccBoolean|1': true,                    // Boolean
    ccId: '@Id',                            // 订单类编号
    ccDatatime: '@datetime',                // 时间字符串
  }]
})

这样我们就可以在请求返回时查看到数据了

常用的数据的Mock方法

ccShow: '123',                          // 所见即所得  

'ccBoolean|1': true,                    // Boolean
ccId: '@Id',                            // 订单类编号
ccDatatime: '@datetime',                // 时间字符串
'ccIndex|1': ['100', '1万条=', '10万'],   // 在指定选项中选取一项
'ccRepetition|1-2': ['100', '1万条'],     // 重复后边内容1-2次 数组内容不是对象
ccInt: '@integer(0, 200)',              // 随机整数 0-200
//ccFloat: '@float(60, 100)',           // 随机浮点数 60 - 100
ccFloat: '@float(60, 100, 0, 3)',       // 随机浮点数 60 - 100 小数点后0-3位

ccProvince: '@province',                //省份
ccCity: '@city',                        // 市 '@city(true)' 省-市 '@county' 区县 '@county(true)' 省-市-县(区)
ccEmail: '@email',                      // 邮箱 太随机用不了
ccString: '@string("abcdefg", 0, 10)',  // 根据给定内容随机生成字符串 长度0-10
ccWord: '@word(3, 10)',                 //  随机长度3-10的字符串
ccCWord: '@cword(3, 10)',               //  随机长度3-10的中文字符串

4.Mock拦截多个ajax请求

题外话: 首先mock给定的拦截ajax请求的方法是Mock.mock这个方式是重载的生成数据也是它。Mock.mock可以有三个参数url, type, function 拦截地址,拦截的请求类型,拦截的处理函数。原生的Mock拦截多个请求多写几个Mock.mock就可以了

首先我这里是对mock进行过封装的,所以拦截多个请求的方法也有些不一样
第一种方式:新建一个类似table的文件,在index.js中引入

const Mock = require('mockjs')
const { param2Obj } = require('./utils')

const user = require('./user')   // 引入新文件
const table = require('./table')

const mocks = [
  ...user,	 // 在这里添加对新文件的遍历 ...表示扩展 
  ...table   // 通过扩展可以支持在table中写多个拦截,也可以在不同文件中写多个拦截
]

第二种方式:在table文件中扩展

module.exports = [
  {
    url: '/api/dome',
    type: 'get',
    response: () => {
      const items = data.items
      return {
        code: '0',
        data: {
          total: items.length,
          items: items
        }
      }
    }
  },
  // 下面就是拦截的/api/dome2 接口
  {
    url: '/api/dome2',
    type: 'get',
    response: () => {
      const items = data.items
      return {
        code: '0',
        data: {
          total: items.length,
          items: items
        }
      }
    }
  },
]

5. 文件和Dome

index.js

const Mock = require('mockjs')
const { param2Obj } = require('./utils')

// const user = require('./user')
const table = require('./table')

const mocks = [
  // ...user,
  ...table   // 通过扩展可以支持在table中写多个拦截,也可以在不同文件中写多个拦截
]

// for front mock
// please use it cautiously, it will redefine XMLHttpRequest,
// which will cause many of your third-party libraries to be invalidated(like progress event).
function mockXHR() {
  // mock patch
  // https://github.com/nuysoft/Mock/issues/300
  Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
  Mock.XHR.prototype.send = function() {
    if (this.custom.xhr) {
      this.custom.xhr.withCredentials = this.withCredentials || false

      if (this.responseType) {
        this.custom.xhr.responseType = this.responseType
      }
    }
    this.proxy_send(...arguments)
  }

  function XHR2ExpressReqWrap(respond) {
    return function(options) {
      let result = null
      if (respond instanceof Function) {
        const { body, type, url } = options
        result = respond({
          method: type,
          body: JSON.parse(body),
          query: param2Obj(url)
        })
      } else {
        result = respond
      }
      return Mock.mock(result)
    }
  }
  // 遍历mocks去拦截请求 默认是get请求
  for (const i of mocks) {
    Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
  }
}

module.exports = {
  mocks,
  mockXHR
}

table.js

const Mock = require('mockjs')

// 详细可参考 http://mockjs.com/examples.html#Basic 
const data = Mock.mock({
  'items|0-20': [{
    ccShow: '123',                          // 所见即所得  

    'ccBoolean|1': true,                    // Boolean
    ccId: '@Id',                            // 订单类编号
    ccDatatime: '@datetime',                // 时间字符串
    'ccIndex|1': ['100', '1万条=', '10万'],   // 在指定选项中选取一项
    'ccRepetition|1-2': ['100', '1万条'],     // 重复后边内容1-2次 数组内容不是对象
    ccInt: '@integer(0, 200)',              // 随机整数 0-200
    //ccFloat: '@float(60, 100)',           // 随机浮点数 60 - 100
    ccFloat: '@float(60, 100, 0, 3)',       // 随机浮点数 60 - 100 小数点后0-3位

    ccProvince: '@province',                //省份
    ccCity: '@city',                        // 市 '@city(true)' 省-市 '@county' 区县 '@county(true)' 省-市-县(区)
    ccEmail: '@email',                      // 邮箱 太随机用不了
    ccString: '@string("abcdefg", 0, 10)',  // 根据给定内容随机生成字符串 长度0-10
    ccWord: '@word(3, 10)',                 //  随机长度3-10的字符串
    ccCWord: '@cword(3, 10)',               //  随机长度3-10的中文字符串
  }]
})

module.exports = [
  {
    url: '/api/dome',
    type: 'get',
    response: () => {
      const items = data.items
      return {
        code: '0',
        data: {
          total: items.length,
          items: items
        }
      }
    }
  },
  {
    url: '/api/dome2',
    type: 'get',
    response: () => {
      const items = data.items
      return {
        code: '0',
        data: {
          total: items.length,
          items: items
        }
      }
    }
  },
]

utils.js

/**
 * @param {string} url
 * @returns {Object}
 */
function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

module.exports = {
  param2Obj
}

Dome:
地址

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

空门.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值