Did a title party (don’t ridicule, say the great truth, really can not background, can take data, fast! , look down…)

What is mock.js?

Website ticket

To briefly describe, mock.js is a handy library of tools that can simulate data locally to test interface functionality when the backend interface is not updated. For more details, check out our website.


Two, installation method

    JS_CDN:  

<script src="https://cdn.bootcss.com/Mock.js/1.0.1-beta3/mock-min.js"></script>Copy the code

   Yarn:

yarn add mockjsCopy the code

Other installation methods can be found on the official website


Three, easy to use tutorial

Mock.mock()

@params rtype {string} request type. If this parameter is not passed, the post/ GET request will get matched data. Note The field must be all lowercase; otherwise, it cannot be matched. @params template {*} Default data (final request return result) @paramsfunction {function} options is the requested data, which can be seen in the following example. This function is not explained herereturn ,returnThe data is the final request result, which can be processed according to the parameters of optionsCopy the code

1. Mock.mock( template )

2. Mock.mock( rurl, template )

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

4. Mock.mock( rurl, rtype, template )

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

For a list of basic uses, see the website for more details.


Mock.setup()

Mock. Setup ({timeout: 400 // Set timeout) Mock. Setup ({timeout: 400 // Set timeout)'300-6000'// interval random timeout})Copy the code


  • Mock.Random(There are many functions, only some commonly used ones are listed.)

Var randomEmail = random.email () var randomBoolean = random.boolean () Var randomUrl = random.url () var randomBase64Img = random.dataimage ( Var randomColor = random.color () var randomColor = random.color () /** @params size {String}'600 X 300'@params background {String} the background color of the generated image defaults to white (RBG) @params text {String} the middle text of the generated image defaults to the size of the image @params format {Sting} the format of the generated image PNG by default (Optional: JPG/PNG/GIF) */ Random. Image () Random. Image (size) Random. Image (size, background) Random. text ) Random.image( size, background, foreground, text ) Random.image( size, background, foreground, format, Text) the official random support function is very powerful, but also very complete, some random functions can support parameter transmission, can define the random data suitable for the scene, because there are too many functions, can not list one by one, can go to the official website to find their own.Copy the code

Official support for random data:Copy the code



Examples in JS

letRandom = Mock.Random // random function // test get Mock. Mock ('/get'.'get',{id: random.id(), name: 'GET', email: random.email()}) // Test post mock.mock ('/post'.'post',{id: random.id(), name: 'POST', email: random.email()}) // Test custom templates mock.mock ('/template'.'post'.function (option) {
  console.log('I am a custom function request parameter:', option)
  let data = {id: 1, name: 'Template',image: random.image()}
  return data
})

  testRequest('/get'.'GET') // Test the Get requesttestRequest('/post'.'POST') // Test the Post requesttestRequest('/template'.'POST', {key: 'Test Params'}) // Test Post request /** * @description: Mock request */function testRequest (url, type,data = {}) {
    let baseUrl = ' '
    $.ajax({
      url: baseUrl + url,
      type: type,
      data: data,
      dataType: 'json',
      success: res => {
        console.log(res)
      },
    })
  }Copy the code



V. Use in Vue

==> mock/index.js 

import Mock from 'mockjs'// Test get Mock. Mock ('/get'.'get',{id: 1, name: 'GET'}) // Test post mock.mock ('/post'.'post',{id: 1, name: 'POST'}) // Test custom templates mock.mock ('/template'.'post'.function (option) {
  console.log('I am a custom function request parameter:', option)
  let data = {id: 1, name: 'Template'}
  returnData}) ==> main.js // reference the mock data file ***** import in the main.js code'./mock/index.js'
*****

import axios form 'axios'// Test the get request axios.get('/get').then(res => {console.log(res)} // Test the POST request axios.post('/post'Then (res => {console.log(res)} // Test custom template request axios.post('/post', {key: 'Test Params'}).then(res => { console.log(res) }
Copy the code

Tread pit note:

  1. The intercepting address of mock.js needs to be consistent with the request address, otherwise the request cannot be intercepted
  2. Mock. Js intercepts requests that do not appear in the network request list.
  3. mock.js Mock.mock(.. Rtype) rtype Parameter Notice The field must be all lowercase; otherwise, the field cannot be matched.


Use extensions

In many cases, the server defines a fixed return value, such as code 0, to indicate that the request is valid. We can then encapsulate a function that will be called each time the data is returned to format the server’s fixed return template.

/** * @description: mock returns data * @param data {*} request data * @param code {number} request status */function formattingData (data, code = 0,msg) {
  return {
    data: data,
    code: code,
    msg: msg || (code === 0 ? 'Request successful' : 'Request failed'}} // Test get Mock. Mock ('/get'.'get',formattingData({id: 1, name: 'GET'}) // Test get request failed mock.mock ('/get/err'.'get',formattingData(undefined,1))Copy the code




Yeah, I’m kidding. If that’s okay, please give me a thumbs up for your typing speed.

! Please indicate the source of reprint