In the development of the front and back end separation, everyone is developed at the same time, often the data interface of the back end is not written immediately. In this case, we need to simulate some data locally to render the page. Mockjs is a good tool.

The installation

npm:

npm install mockjs --save-dev
Copy the code

yarn:

yarn add mockjs --dev
Copy the code

use

Let’s start with an official example:

/ / use the Mock
var Mock = require('mockjs')
var data = Mock.mock({
    The value of the attribute list is an array of 1 to 10 elements
    'list|1-10': [{
        // Attribute id is an increment, starting at 1 and incrementing by 1 each time
        'id|+1': 1}]})// Output the result
console.log(JSON.stringify(data, null.4))
Copy the code

Let’s take a look at the Mockjs features.

mock

A mock method is a method that mocks a data interface and takes three arguments:

  • Url: address of the simulated interface;
  • Type: request type.
  • The template | function (options) : record is used to generate the response data object or function.

Function of the third parameter is not used, interested to see Mockjs official website

Example:

Mock.mock('/api/article'.'get', {name: 'Force the Universe'.type: 'I'
})
Copy the code
  1. I simulated one above/api/articleInterface, no writehostIf I use Vue scaffolding here, the default is scaffolding up servicehostBut in fact, you can’t request the address directly by typing it into the browser.becauseMockjsIt just intercepts the request from the front end and returns simulated response data.
  2. Request mode, defaultget, can not pass;
  3. mockThe third parameter to a method is the simulated data, which is a method or object, more on that later.
  4. The requested address can be dynamically matched by passing a regular expression.

Dynamic matching:

Mock.mock(/\/api\/art/, {
  name: 'Force the Universe'.type: 'I'
})
Copy the code

This also matches the/API /article interface.

setup

Configure the behavior when intercepting Ajax requests. Supported configuration items:

Timeout: The only one I’ve seen so far. This is the response time configuration, which indicates how long it takes to return a request, in milliseconds

Random

This is a nice thing, it’s a random data generator.

The official website to the method:

type methods
Basic boolean, natural, integer, float, character, string, range, date, time, datetime, now
Image image, dataImage
Color color
Text paragraph, sentence, word, title, cparagraph, csentence, cword, ctitle
Name first, last, name, cfirst, clast, cname
Web url, domain, email, ip, tld
Address area, region
Helper capitalize, upper, lower, pick, shuffle
Miscellaneous guid, id

See Mockjs’ official website for more details. Here are a few examples:

  1. Generate random numbers or objects:

    ‘page | 18 to 25:25: the generated between the age of 18 to 25, and value behind it doesn’t matter;

    ‘the user | 1-3’ : [{name: ‘author’}] : generates an array, there is 1-3 object;

  2. Random generation time:

    birthday: '@datetime'

  3. Generate random Chinese name:

    name: '@cname'

In addition to what is already built into Mockjs, you can define Random yourself, for example:

Mock.Random.extend({
  constellation: function() {
      var constellations = ['Aries'.'Taurus'.'Gemini'.'Cancer'.'狮子座'.'Virgo'.'Libra'.'Scorpio'.Sagittarius.'Capricorn'.'Aquarius'.'Pisces']
      return this.pick(constellations)
  }
})
Copy the code

Use the same as before:

constellation: '@constellation'

Finally, see an example, feel good, post it,

import Mock from 'mockjs' / / introduce mockjs
 
const Random = Mock.Random // Mock.Random is a utility class for generating Random data of various kinds
 
let data = [] // The array used to accept the generated data
let size = [
  '300x250'.'250x250'.'240x400'.'336x280'.'180x150'.'720x300'.'468x60'.'234x60'.'88x31'.'120x90'.'120x60'.'120x240'.'125x125'.'728x90'.'160x600'.'120x600'.'300x600'
] // Define random values
for(let i = 0; i < 10; i ++) { // The number can be customized
  let template = {
    'Boolean': Random.boolean, // Basic data types can be generated
    'Natural': Random.natural(1.10), // Generate natural numbers between 1 and 100
    'Integer': Random.integer(1.100), // Generate an integer between 1 and 100
    'Float': Random.float(0.100.0.5), // Generates floating point numbers between 0 and 100, with 0 to 5 digits after the decimal point
    'Character': Random.character(), // Generate random string, can be added to define rules
    'String': Random.string(2.10), // Generates a string between 2 and 10 characters
    'Range': Random.range(0.10.2), // Generate a random number group
    'Date': Random.date(), // Generate a random date with parameters to define the date format
    'Image': Random.image(Random.size, '#02adea'.'Hello'), // Random. Size indicates that any data will be selected from the size data
    'Color': Random.color(), // Generate a random color value
    'Paragraph':Random.paragraph(2.5), Generate 2 to 5 sentences of text
    'Name': Random.name(), // Generate the name
    'Url': Random.url(), // Generate a Web address
    'Address': Random.province() // Generate the address
  }
  data.push(template)
}
 
Mock.mock('/data/index'.'post', data) // Generate simulated data from the data template
Copy the code

Isn’t that easy to use? Over.