This is the 15th day of my participation in the August Text Challenge.More challenges in August

In the old days when the front and back end were not separated, writing pages was an effort, and when there were data problems, you had to go looking for this and that.

Fortunately, the separation of front and back ends is now very mature, and the fear that the front end was dominated by the back end is gone forever. So speaking of the front and back end separation, I have to talk about the simulation data.

In a normal development process, the front end is usually a billion points faster than the back end

So caused the front-end page style to write almost, just waiting for data rendering to see the logic, the results of the dark off work back end to an interface document.

Just wide of the mark

So pretty soon, someone came up with mock. js, which makes it very easy to generate any data you need.

1, install,

npm i mockjs -D
Copy the code

2, use,

/ / introduction
const Mock = require('mockjs')

If fn is passed in, the value returned by fn is returned; otherwise, the value generated from template is returned
constdata = Mock.mock(rurl? , rtype? , template|function( options ))
console.log(JSON.stringify(data, null.4))
Copy the code

3, grammar,

The syntax consists of two things: DTD (Data Template Definition Specification) and DPD (Data placeholder Definition Specification)

3.1 the DTD

Each attribute of a data template consists of three parts: attribute name, generation rule, and attribute value

  • Attribute name: name
  • Generate rule: rule
  • Attribute value: value

Writing format:

‘name|rule’: value

3.1.1 Generating Rules

There are seven types of generation rules:

  • ‘name|min-max’: value
  • ‘name|count’: value
  • ‘name|min-max.dmin-dmax’: value
  • ‘name|min-max.dcount’: value
  • ‘name|count.dmin-dmax’: value
  • ‘name|count.dcount’: value
  • ‘name|+step’: value

The meaning of each rule depends on the type of the attribute value

Example:

  1. The property value is a String

‘name | min – Max’ : a string, through repeated string to generate a string, repeat number greater than or equal to the min, less than or equal to Max

‘name | count’ : a string, through repeated string to generate a string, repetition frequency is equal to the count

  1. The property value is the Number

‘name | + 1’ : automatically add 1 number attribute values, the initial value for the number

‘name | min – Max’ : number generated a greater than or equal to min, an integer less than or equal to Max, the attribute value number is used to determine the type

‘name | min – Max. Dmin -‘ on3dmax, generated a floating-point number, the integer part is greater than or equal to less than Max, min, the decimal part dmin to on3dmax digits

  1. The property value is Boolean

The name ‘| 1’ : Boolean randomly generated a Boolean value, the probability that the value is true is 1/2, the probability of a false value also is 1/2.

‘name | min – Max’ : the value randomly generated a Boolean value, the value of the value of the probability is min / + Max (min), value of! The probability of value is Max over min plus Max.

  1. The property value is the Object

‘name | count’ : the object property values count a randomly selected in the object properties

‘name | min – Max’ : the object in the object property values randomly selected to Max min properties

  1. The property value is Array Array

The name ‘| 1’ : an array property values randomly selected one element in an array, as the final value.

‘name | + 1’ : array order to select one element in an array property values, as the final value.

‘name | min – Max’ : array by repeating array to generate a new array attribute values, repeat number greater than or equal to the min, less than or equal to Max.

‘name | count’ : array by repeating array to generate a new array attribute values, repetitions for the count

  1. The property value is Function

‘name’: function Executes the function function, taking its return value as the final property value, and the context of the function is the object in which the property ‘name’ resides

  1. The property value is the regular expression RegExp

‘Name ‘: regexp Generates a string that matches the regular expression regexp in reverse. String used to generate custom formatting

3.2 DPD

Placeholders simply take a place in the attribute value string and do not appear in the final attribute value.

  • The reference isMock.RandomThe methods in
  • The @ symbol identifies the string that follows as a placeholder
  • Placeholders can reference and preferentially reference properties in the data template
  • throughMock.Random.extend()To extend custom placeholders

Writing format:

@ placeholder @ placeholder (parameter [, parameter])

3.2.1 Built-in placeholders
Type Methord
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

In the ordinary analog interface data, the use of placeholders is more often used to generate data.

For example, placeholders can reference and preferentially reference attributes in a data template:

Mock.mock({
    name: {
        first: '@first'.middle: '@cfirst'.last: '@last'.full: '@first @middle @last'  // The placeholder here refers to the attribute value in the template}})/ / = >
{
    "name": {
        first: "Matthew"
		full: "Matthew Robinson du"
		last: "Robinson"
		middle: "Du"}}Copy the code

Visit jump for more examples

3.2.2 Extending custom placeholders
let Random = Mock.Random
Random.extend({
    constellation: function(date) {
        let constellations = ['Aries'.'Taurus'.'Gemini'.'Cancer'.'狮子座'.'Virgo'.'Libra'.'Scorpio'.Sagittarius.'Capricorn'.'Aquarius'.'Pisces']
        return this.pick(constellations)
    }
})
Random.constellation()    // => "Aquarius"
Mock.mock('@CONSTELLATION')   // => "Scorpio"
Mock.mock({
    constellation: '@CONSTELLATION'
})    // => {constellation: "Sagittarius"}
Copy the code

4, API

Mock exposes few methods, only Mock, setup, Random, Valid, and toJSONSchema.

API describe parameter
mock Used to generate and return simulated data rurl: Indicates the URL to be intercepted. It can be a URL string or A URL re. For example, ‘/domian/list.json’ and //domain/list.json/.

rtype: Optional, indicates the type of Ajax request to intercept. For example, GET, POST, PUT, and DELETE.

template: Indicates an optional data template, which can be an object or a string. Data such as {‘ | 1-10 ‘: [] {}},’ @ EMAIL, etc.

function(options): Optional, representing the function used to generate the response data. Options. See AlsoThe XMLHttpRequest specification.
setup Configure the behavior when intercepting Ajax requests settings: Indicates a parameter set. This parameter is mandatory. For example, {timeout: ‘200-600’}.
valid Verify that the real data data matches the data template template: Indicates a data template. It can be an object or a string. For example {‘list| 1-10’:[{}]}, ‘@email’.

data: Mandatory, indicates real data.
toJSONSchema Convert the Mock. Js-style data template toJSON Schema template: Indicates a data template. It can be an object or a string. For example {‘list| 1-10’:[{}]}, ‘@email’.
Random A utility class for generating various random data

5. More examples

Reference: mockjs.com/examples.ht…