Playing with Mockjs, the front end can run very smoothly

Posted by el_quijote on Sat, 11 Dec 2021 00:09:59 +0100

The function of mockjs is to generate random simulation data, intercept ajax requests, and add, delete, modify and query the data. When generating data, we need to be able to skillfully use mock JS syntax.

The syntax specification of Mockjs includes two parts: data template definition specification and data placeholder definition specification.

1, Data template definition specification

Each attribute in the data template consists of: attribute name, generation rule and attribute value.

The usage syntax is:

"name|rule": value

Notable are:

  • A | split is used between the attribute name and the generation rule.
  • The build rule is an optional parameter.
  • There are seven forms of generation rules.
  • The meaning of the generation rule needs to depend on the type of attribute value.
  • Property values can specify initial values and types.

The formats for generating rules are:

1.1. The attribute value is of type String

The number of repetitions of a variable is a random value.

'name|min-max':string
 By generating a string repeat min reach max A string between..

//use
'name|1-3':'a'
Run result: generate a a The number of is 1-3 String variables between. Possible results are: a,aa ,aaa

Specify the number of repetitions directly.

'name|count':string
 By generating a string repeat count A string of times..

//use
'name|3':'a'
Operation results: aaa

1.2. The attribute value is Number

Generate cumulative numbers.

'name|+1':num
 The initial value is num ,The generated attribute value is automatically incremented by 1

Generate an interval value.

'name|min-max':num
 Generate a min reach max Values between, num Used to specify the type

//use
'name|1-3': 1
 Run result: generate a 1-3 Number between. Possible results are: 1, 2, 3

Generates a number with a decimal point.

'name|min-max.dmin-dmax': num
 Generates a floating-point number with an integer part between min and max Between, decimal retention dmin reach dmax Bit. num Used to specify the type.

//use
'num1|1-10.1-2': 1
 Run result: generate 1-10 Floating point number with 1 to 2 decimal places between. For example: 2.1,3.12 etc.

'num2|5.1-2': 1
 Generate an integer part of 5 ,Floating point numbers with 1 to 2 decimal places. For example: 5.1,5.33,5.09 etc.

'num3|5.2': 1
 Generates a floating-point number with an integer of 5 and two decimal places. For example: 5.11,5.67 etc.

1.3. The attribute value is Boolean

'name|1': boolean
 Generate a random value, and the probability of true and false is half.

//use
'isLike|1': true
 generate isLike The value of may be true ,false. The probability is the same.
'name|min-max': value
 Randomly generate a Boolean value,
Value is value The probability is min / (min + max),
Value is !value The probability is max / (min + max). 

//use
'like|1-5': true
 generate true The probability of is 1/6 . generate false The probability is 5/6

1.4. The attribute value is Object

Generates an object with a specified number of attributes.

'obj|num': object
 Slave attribute value object Random selection num Attributes.

//use
'obj|2': {
             a: '1',
             b: '2',
             c: '3'
            }
The operation results may be:
{a: "3", b: "2"}
{c: "3", b: "2"}
{a: "3", c: "2"}

Generate an object with a random number of attributes.

'obj|min-max': object
 from object Random selection in min reach max Attributes to generate an object.

//use
'obj|1-2': {
             a: '1',
             b: '2',
             c: '3'
            }
The operation results may be:
{a: "3"}
{b: "3"}
{c: "3"}
{a: "3", b: "2"}
{c: "3", b: "2"}
{a: "3", c: "2"}

1.5. The attribute value is Array array

Take an element in the array as the result.

'arr|1':array
 Slave attribute value array Randomly select an element from the list as the result

//use
'arr|1':[1,2,3]
The operation results are: 1, 2 and 3

Generate a new array.

'arr|min-max': array
 By repetition array Generate a new array of elements, number of repetitions min reach max . 

//use
'arr|1-2': [ 1,2,3 ]
The operation result is:[ 1,2,3 ] or [ 1,2,3,1,2,3 ]
'arr|num': array
 By repetition array Generate a new array of elements, number of repetitions num Times.

//use
'arr|2': [ 1,2,3 ]
The operation result is: [ 1,2,3,1,2,3 ]

1.6. Attribute value is Function

'name':function
function Returns the value as the final property value.

//use
'name': ()=>{
 return 'web learn'
}
The running result is web learn

In the data placeholder, the attribute value is a function, which is of great significance. It will be explained later.

1.7. The attribute value is regular RegExp

'name': regexp
 According to regular expression regexp Reverse generates a string that can be matched. String used to generate custom format

//use
'reg': /[a-zA-Z0-9]2/
Generates a string of length 2 composed of upper and lower case letters and numbers

'reg':/\d{5,10}/
Generate any 5 to 10 digit numeric string

2, Data placeholder definition specification

The data placeholder just takes a place in the attribute string and does not appear in the final attribute value.

Use format:

@placeholder 
@placeholder (parameter [, parameter])

//use
'name': "@name",
 Generate English name, such as: Edward Rodriguez

//With parameters
'first':"@name(middle)",
Generate an English name with a middle name. For example: Ruth Paul Robinson

'name': "@cname",
 Generate Chinese name

be careful:

  • The string identified by @ is an identifier.
  • Placeholders refer to mock Methods in random.
  • If you need to extend a custom placeholder, use mock Random. extend().
  • Placeholders can also reference content in the data template.
  • Placeholders take precedence over attributes in the data template.
  • Relative and absolute paths are supported.
Mock.mock('@string("number", 5)')
Generates a five digit string

Mock.mock('@color')
Generate random colors
//Equivalent to
Random.color()

3, Use examples

Create an api interface and return a randomly generated array:

export default [
 {
  url: "/api/list",
  method: "post",
  response: ({ url, body }) => {
   // body is the data passed in when using the post method
   // url is the request interface. When using get method, it also contains the passed parameters
   return {
    code: 200,
    message: "ok",
    //Generate an array
    // Length between 10 and 20
    'list|10-20': [{
     name:'@cname' //Generate Chinese name
    }]
   };
  }
 }
]

Placeholders refer to mock The method in random, so we can change the above code to:

'list|10-20': [{
 name:Random.cname() //Generate Chinese name
}]

As like as two peas, we found that the names of the generated arrays were identical. If we want to generate different names, how to solve it?

Solution: change the attribute value to a function and take the return value of the function as the final result.

'list|10-20': [{
 name:()=>{
  Random.cname()
 } 
}]

Well, Xiaobian, this is the end of today's article. Those who like me can pay attention!

Topics: Front-end mock