What is a MockJS
In a development environment that separates front and back ends, front-end students need to wait for back-end students to provide interfaces and interface documents before continuing development. MockJS allows the front-end student to develop independently of the back-end student, by first teasing out the interface document based on the business and using MockJS to simulate the back-end interface. So how does MockJS simulate the back-end interface? MockJS simulates the interface provided by the backend students by intercepting specific AJAX requests and generating random numbers for a given data type.
The preparatory work
At the top: For those of you who may not be familiar with deploying front-end environments, I uploaded the code to Github. If you need it, download it and read the tutorial below.
First install MockJS, and install AxiOS to test the simulated interface by sending AJAX requests. Using other methods such as native AJAX requests or $. AJAX is fine, and sending AJAX requests by other means does not require installing AxiOS.
npm install mockjs --save
npm install axios --save
Copy the code
Package the vue single file using the WebPack packaging tool. First install csS-Loader, style-Loader, vue, vue-Loader, and vue-template-compiler.
npm install css-loader style-loader --save-dev
npm install vue vue-loader vue-template-compiler --save-dev
Copy the code
Then add the loader to the webpack.config.js configuration file. The complete configuration is shown below.
const path = require("path");
const {VueLoaderPlugin} = require('vue-loader');
module.exports = {
entry: './webapp/App.js',
output: {
filename: 'App.js',
path: path.resolve(__dirname, './dist')
},
module: {
rules: [
{
test: /\.css/,
use: ['style-loader'.'css-loader'] {},test: /\.vue$/,
use: 'vue-loader'
}
]
},
plugins: [
new VueLoaderPlugin()
],
mode: "production"
}
Copy the code
Create a mock.js file and import it in the entry file (main.js).
require('./mock.js');
Copy the code
Introduce MockJS in the mock.js file.
import Mock from 'mockjs';
Copy the code
We’ll write the mock interface in mock.js later.
The directory structure is as follows:
The official start of the
MockJS has two ways to define the data returned by the mock interface: using a data template definition, which has the freedom to customize various Random data types, or using a method definition of MockJS’s Random utility class, which has the freedom to define only the Random data types provided by MockJS. 2. Use the Rndom utility class to define the return value of the mock interface.
1. The data template defines the return value of the simulated interface
Let’s take an example
//mock. Js data template {'string|1-10':'string'} // Generated data returned by the interface ===> {'string':'stringstringstring'
}
Copy the code
The format of the data templates for ‘attribute name | rules’ :’ attribute values, to generate rule determines the attribute value of the resulting data. There are altogether 7 generation rules, which are:
- ‘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
For different data types, you can use different generation rules. The data type of the property value can be Number, Boolean, String, Object, Array, Function, Null, and cannot be Undefined. In the following, I will use 7 generation rules for each data type to see which generation rules can be used for each data type. Those who want to see the conclusion directly pull it to the table in 1.8.
1.1 ‘name | min – Max’ : the value
Before you start, you can go to my Github to download the project and run it. The combined project is more intuitive, and you can learn what kind of data is randomly selected by each generation rule through refreshing.
In the mock.js file, define an array data1 to hold the randomly generated property values, then define an object row1 to hold the generated property values, and then define the mock interface. In app.vue, use Axios to make a request to the mock interface and display the data in a table.
const data1=[]; // Data template'name|min-max':value
let row1={
'string|1-9':'string'.'number|1-9': 1,'boolean|1-9':false.'undefined|1-9':undefined,
'null|1-9':null,
'object|1-9':{object1:'object1',object2:'object2',object3:'object3'},
'array|1-9': ['array1'.'array2'].'function|1-9': () = >'function'}; data1.push(row1); // Define the Mock interface to receive only POST requests, and define the data returned as data1 mock.mock ('/Get/list1'.'post',data1);
Copy the code
For numeric values, it randomly generates 1-9 values.
For Boolean types the min/(min+ Max) probability generates value, and the Max /(min+ Max) probability generates! Value, I’m saying 10% false,90% true.
The undefined value is simply ignored, and the generated object does not have the undefined attribute name.
The value generated for NULL is NULL.
For an object, a value value is randomly generated in min-max, and then the value attributes of the object are selected to form a new object. If the value is greater than the number of attributes of the object, all the attributes are taken out. It can be seen in the figure that all the attributes of the object are taken out to form a new object.
For the array, a value is randomly generated in min-max, and then the array elements are repeated with value several times and merged into an array. As can be seen in the figure, the random value is 6, and six arrays are merged to produce a new array.
For functions, the function is executed directly and its value is returned.
1.2 the name ‘| count’ : the value
// Data template'name|count':value
let row2={
'string|3':'string'.'number|3': 1,'boolean|3':false.'undefined|3':undefined,
'null|3':null,
'object|3':{object1:'object1',object2:'object2',object3:'object3'},
'array|3': ['array1'.'array2'].'function|3': () = >'function'
};
data1.push(row2);
Copy the code
| count rule for string it is concluded that the new string is a repeat count time, can be seen in the figure repeated 3 times.
For numeric values it is generated with a value of count.
For Boolean types that are (count-1)/count probabilities generate value values, 1/count probabilities generate! Value, I have a 66.7% probability of false and 33.3% probability of true.
The undefined value is simply ignored, and the generated object does not have the undefined attribute name.
The value generated for NULL is NULL.
For an object, select the number of properties of the object to form a new object. If the count is greater than the number of properties of the object, all properties are taken out. In the figure, it can be seen that all properties of the object are taken out to form a new object.
In the case of an array, repeat the elements of the array count several times and then merge them into one array. As you can see in the figure, the random number is 3, and then merge the three arrays into a new array.
For functions, the function is executed directly and its value is returned.
1.3 ‘name | min – Max. Dmin – on3dmax’ : the value
// Data template'name|min-max.dmin-dmax':value
let row3={
'the string | 1-9.1-9':'string'.'number | 1-9.1-9':1, // Only the value counts'the Boolean | 1-9.1-9':false.'the undefined | 1-9.1-9':undefined,
'null | 1-9.1-9':null,
'the object | 1-9.1-9':{object1:'object1',object2:'object2',object3:'object3'},
1-9.1-9 'array |': ['array1'.'array2'].'the function | 1-9.1-9': () = >'function'
};
data1.push(row3);
Copy the code
| min – Max. Dmin – rules for string is | on3dmax min – Max rules.
For numeric values, it is to generate a floating point number whose integer part is min-max and whose decimal place is dmin-dmax. The figure generates a value of 3.59 with integer digit 3 and decimal digit 2.
The Boolean type is | min – Max rules
The undefined value is simply ignored, and the generated object does not have the undefined attribute name.
The value generated for NULL is NULL.
For the object is | min – Max rules
For the array is also | min – Max rules
For functions, the function is executed directly and its value is returned.
1.4 ‘name | min – Max. Dcount’ : the value
// Data template'name|min-max.dcount':value
let row4={
'the string | 1-9.3':'string'.1-9.3 ' 'number |:1, // Only the value counts'the Boolean | 1-9.3':false.'the undefined | 1-9.3':undefined,
'null | 1-9.3':null,
'the object | 1-9.3':{object1:'object1',object2:'object2',object3:'object3'},
'array | 1-9.3': ['array1'.'array2'].'the function | 1-9.3': () = >'function'
};
data1.push(row4);
Copy the code
| min – Max. Scount rules for string is | min – Max rules.
For numeric values, it is to generate a floating point number whose integer part is min-max and whose decimal place is scount. The figure generates a value of 6.725 with integer 6 and decimal 3.
The Boolean type is | min – Max rules
The undefined value is simply ignored, and the generated object does not have the undefined attribute name.
The value generated for NULL is NULL.
For the object is | min – Max rules
For the array is also | min – Max rules
For functions, the function is executed directly and its value is returned.
1.5 ‘name | count. Dmin – on3dmax’ : the value
// Data template'name|count.dmin-dmax':value
let row5={
'the string | 3.1-9':'string'.'number | 3.1-9':1, // Only the value counts'the Boolean | 3.1-9':false.'the undefined | 3.1-9':undefined,
'null | 3.1-9':null,
'the object | 3.1-9':{object1:'object1',object2:'object2',object3:'object3'},
'array | 3.1-9': ['array1'.'array2'].'the function | 3.1-9': () = >'function'
};
data1.push(row5);
Copy the code
| count. Dmin – rules for string is | on3dmax count rules.
For numeric values, a floating point number is generated, with the integer part of the value being count and the decimal place being the dmin-dmax bit. The figure generates the value 3.035354 with integer digit 3 and decimal digit 6.
The Boolean type is | count rules
The undefined value is simply ignored, and the generated object does not have the undefined attribute name.
The value generated for NULL is NULL.
For object is | count rules
For the array is also | count rules
For functions, the function is executed directly and its value is returned.
1.6 ‘name | count. Dcount’ : the value
// Data template'name|count.dcount':value
let row6={
'the string | 3.3':'string'.'the number 3.3 |':1, // Only the value counts'the Boolean | 3.3':false.'the undefined | 3.3':undefined,
'null | 3.3':null,
'the object | 3.3':{object1:'object1',object2:'object2',object3:'object3'},
'array | 3.3': ['array1'.'array2'].'the function | 3.3': () = >'function'
};
data1.push(row6);
Copy the code
| count. Dcount rules for string is | count rules.
For numeric values, a floating point number is generated, with the integer part of the value being count and the decimal place being dcount bits. The figure generates the value 3.425 with integer digit 3 and decimal digit 3.
The Boolean type is | count rules
The undefined value is simply ignored, and the generated object does not have the undefined attribute name.
The value generated for NULL is NULL.
For object is | count rules
For the array is also | count rules
For functions, the function is executed directly and its value is returned.
1.7 ‘name | + step’ : the value
// Data template'name|+step':value
let row7 = {
'string|+3': 'string'.'number|+3': 1, // Only the value counts'boolean|+3': false.'undefined|+3': undefined,
'null|+3': null,
'object|+3': {
object1: 'object1',
object2: 'object2',
object3: 'object3'
},
'array|+3': ['array1'.'array2'].'function|+3': () = >'function'
};
data1.push(row7);
Copy the code
| + step rules for string is no role, directly to the string.
For the value, the initial value is the preset value 1, and the value will increase by a step value every time the request is made again. After clicking the button below, the value will increase by 3 to 4.
It has no effect on Boolean types. The Boolean value is returned directly.
The undefined value is simply ignored, and the generated object does not have the undefined attribute name.
The value generated for NULL is NULL.
It has no effect on the object, just return the object.
For the array, return the value of the array index with 0 on the first request, and increase the index by a step each time the request is made again. For example, after clicking the button once, the index value is 0+3=3, which exceeds the maximum index of the array 1. In this case, subtract the array length by 2 from the index value until the index value is within the maximum index of the array, 3-2=1. Click the button once to return the value of the array subscript 1.
For functions, the function is executed directly and its value is returned.
1.8 summarize
String | Number | Boolean | Undefined | Null | Object | Array | Function | |
---|---|---|---|---|---|---|---|---|
|min-max | The string is repeated min-max times before concatenation to produce a new string | The value of min-max is randomly obtained | Min /(min+ Max) probability generates value value, Max /(min+ Max) probability generates! The value value | The current data type is invalid | Returns a null value | Firstly, a value value is randomly generated in min-max, and then the value attributes of the object are selected to form a new object. If the value is greater than the number of attributes of the object, all the attributes are taken out | A random value is generated in min-max, then the array elements are repeated several times and merged into an array | Executes the function directly and returns its value |
|count | The string is repeated count times to get a new string | Generates a numeric value with the value count | (count-1)/count probability to generate value, 1/count probability to generate! The value value | The current data type is invalid | Returns a null value | Select the count attributes of the object to form a new object. If the count is greater than the number of attributes of the object, all the attributes are taken out | Repeats the array elements count times and merges them into an array | Executes the function directly and returns its value |
|min-max.dmin-dmax | The same as the rules | min – Max | Generates a floating point number whose integer part is min-max and whose decimal place is dmin-dmax | The same as the rules | min – Max | The current data type is invalid | Returns a null value | The same as the rules | min – Max | The same as the rules | min – Max | Executes the function directly and returns its value |
|min-max.dcount | The same as the rules | min – Max | Generates a floating-point number whose integer part is min-max and whose decimal place is dcount | The same as the rules | min – Max | The current data type is invalid | Returns a null value | The same as the rules | min – Max | The same as the rules | min – Max | Executes the function directly and returns its value |
|count.dmin-dmax | The same with | count rules | Generates a floating-point number whose integer part has a value of count and whose decimal place is a dmin-dmax bit | The same with | count rules | The current data type is invalid | Returns a null value | The same with | count rules | The same with | count rules | Executes the function directly and returns its value |
|count.dcount | The same with | count rules | Generates a floating point number with the value of count for the integer part and dcount for the decimal place | The same with | count rules | The current data type is invalid | Returns a null value | The same with | count rules | The same with | count rules | Executes the function directly and returns its value |
|+step | No action, return value directly | The initial value is the default value, which is incremented by a step value each time the request is made again | No action, return value | The current data type is invalid | Returns a null value | No action, return value | The initial value is the subscript is the value of the default value, and the subscript value will be increased by a step value each time the request is made again | Executes the function directly and returns its value |
Including | min – Max. Dmin on3dmax, | min Max. Dcount, | count. Dmin on3dmax, | count. Dcount these four rules are mainly used to Number types.
2. Use the Random utility class to define the return value of the mock interface
MockJS provides a set of methods that let us quickly and randomly figure out the data we want.
const Random=Mock.Random;
{
'Boolean'Boolean, // Generate Boolean types randomly'Natural': Random. Natural (1, 100), // Generate natural numbers between 1 and 100 randomly'Integer': Random. Integer (1, 100), // Generates an integer between 1 and 100'Float': random.float (0, 100, 0, 5), // Generates a floating point number between 0 and 100, with a mantail of 0 to 5 bits after the decimal point'Character': random.character (), // generates a Random string. Parameters 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), // Generates an array with elements starting at 0 and ending at 10, spaced by 2'Date': random.date (), // generates a Random date. You can add parameters to define the date format. The default is YYYY-MM-dd'Image1': Random.image(Random.size, '#02adea'.'#fff'.'png'.'Hello'), // Random. Size indicates that Random data will be selected from the size data and generated with the size specified by Random'#02adea'The foreground scenery is'#fff', the format is'png'Of, the content is'Hello'The images.'Image2':Random.dataImage('200x100'.'Hello Mock.js! '),// Only set the size'Color': random.color (), // generates a Random value for the color'Paragraph':Random. Paragraph (2, 5), // Generates text of 2 to 5 sentences'Name': random.name (), // generates the name'Url': random.url (), // generates the URL address'Address': random.type () // generate address}Copy the code
Once the data is organized, you also need to set up the emulation interface.
Mock.mock('/Get/list2'.'post', data2) ;
Copy the code
This interface is then accessed through AJAX to get the mock data.
Complete code:
//mock.js
const Random = Mock.Random;
letData2 = [] // Used to accept an array of generated datalet size = [
'300x250'.'250x250'.'240x400'.'336x280'.'180x150'.'720x300'.'468x60'.'234x60'.'88x31'.'120x90'.'120x60'.'120x240'.'125x125'.'728x90'.'160x600'.'120x600'.'300x600'] // Define a random valuefor(leti = 0; i < 10; I ++) {// generate 10 objects and put them in an arraylet template = {
'Boolean': Random. Boolean, // can generate basic data types'Natural': Random. Natural (1, 100), // generates a natural number between 1 and 100'Integer': Random. Integer (1, 100), // Generates an integer between 1 and 100'Float': random.float (0, 100, 0, 5), // Generates a floating point number between 0 and 100, with a mantail of 0 to 5 bits after the decimal point'Character': random.character (), // generates Random characters. Parameters can be added to define rules'String': random.string (2, 10), // Generates a string between 2 and 10 characters'Range': Random. Range (0, 10, 6), // generate a Random number group'Date': random.date (), // generates a Random date with parameters defining the date format'Image': Random.image(Random.size, '#02adea'.'#fff'.'png'.'Hello'),
'Color': random.color (), // generates a Random value for the color'Paragraph':Random. Paragraph (2, 5), // Generates text of 2 to 5 sentences'Name': random.name (), // generates the name'Url': random.url (), // generates the Web address'Address'} data2.push(template)} Mock. Mock (data2.push(template))'/Get/list2'.'post', data2) // Declare the mock interface // app.vue axios('/Get/list2').then(res => {
this.dataShow2 = res;
});
Copy the code
3. Define the analog interface return value with data placeholders
Using data placeholders to define simulated data can be more concise than the Random utility class.
{
'Boolean': '@boolean', // Randomly generate a Boolean type'Natural': '@natural(1, 100)', // Randomly generate natural numbers between 1 and 100'Integer': '@integer(1, 100)', // Generates an integer between 1 and 100'Float': '@float(0, 100, 0, 5)', // Generates a floating point number between 0 and 100 with a mantissa of 0 to 5 bits after the decimal point'Character': '@character("aeiou")', // In aEIou, random characters are generated. If no parameter is passed, random characters are generated'String': '@string( 2, 10)', // Generates a string between 2 and 10 characters'Range': '@range(0, 10, 2)', // Generates an array with elements starting at 0 and ending at 10 spaced by 2'Date': '@date("yyyy yy y MM M dd d")'// Generate a random date with parameters defining the date format. The default is YYYY-MM-dd'Color1': '@color', // generates a random hexadecimal value for the color'Color2': '@rgb', // generates an RGB random value for the color'Paragraph':'@paragraph(2, 5)', // generate text of 2 to 5 sentences'Sentence':'@sentence(3, 5)', // Generate a sentence of 3 to 5 words'World':'@word(3, 5)', // generate a 3-5 letter word'title':'@ the title (3, 5)', // Generate a 3-5 word heading'cParagraph':'@cparagraph(2, 5)', // Generate 2 to 5 sentences of Chinese text'cSentence':'@csentence(3, 5)', // Generate a Chinese sentence composed of 3 to 5 words'cWorld':'@cword(3, 5)', // Generate Chinese words composed of 3-5 characters'ctitle':'@ ctitle (3, 5)', // Generate a 3-5 words Chinese title'Name': '@name', // generate the name'cName': '@cname', // generate the Chinese name'Url': '@url', // Generate the URL address'Email':'@email',// generate the mailbox'Address': '@county(true)', // generate an address composed of provinces, cities and counties'Guid':'@guid()'// generate the Guid value}Copy the code
summary
MockJS makes the separation more intense, and I think most importantly it gets the front end people thinking about the business as well. In traditional development, the front end staff mostly wait for the interface and interface document provided by the back end staff, and do not know how to actively organize the interface document. Using MockJS, the back end staff can better participate in the project from the perspective of the whole project.
communication
If this article helps you, feel good if you want to point a Star. github.com/lizijie123