MockJS Quick Start

What is MockJS

After separation of the back-end development environment front, the front end gives the students the students need to wait for back-end interfaces and interface documentation, in order to continue to develop. The MockJS allows students to independently develop front-end to back-end students, students can first sort the tip according to the service interface documentation and the use MockJS analog back-end interface. So MockJS backend interface is how to simulate it? MockJS by blocking specific AJAX request, and generates a given data type of random numbers, in order to provide students rear analog interface.

Ready to work

Write on top: Some small partners may not deploy front-end environment, and here I will upload the code to github , there is little need partners can download the code, the code to see shining tutorial below.

First mounting MockJS, is mounted Axios AJAX request to transmit analog test interface, the use of other means such as native or AJAX request $ .ajax are possible, other ways without installing AJAX request sent axios.

npm install mockjs --save
npm install axios --save
复制代码

Use webpack packaging tools packaged vue single file. First install css-loader, style-loader, vue, vue-loader, vue-template-compiler.

npm install css-loader style-loader --save-dev
npm install vue vue-loader vue-template-compiler --save-dev
复制代码

Was then added in the corresponding loader webpack.config.js profile, complete configuration as FIG.

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"
}
复制代码

Mock.js create a file, and then (main.js) introduced at the inlet file.

require('./mock.js');
复制代码

MockJS introduced in mock.js file.

import Mock from 'mockjs';
复制代码

Later we will write in mock.js the analog interface.

Directory structure is as follows:

index.html file is the home page, main.js entrance file, mock.js is an analog interface file, webpack.config.js is webpack profile,. / dist / main.js entry file is packetized,. / src / axios / api.js Axios requested file package.

Officially begin

There are two ways to define data MockJS analog interface returns a data template definition is used, a large degree of freedom in this way, can customize random data types, one is a method using Random MockJS definition tools, in this way the degree of freedom is small, only the random data type MockJS provided. Hurry small partner can skip 2. Use tools Rndom analog interface defines the return value.

1. The data template definition analog interface Return Value

First give an example

//mock.js数据模板
{
    'string|1-10':'string'
}
//接口返回的生成的数据===>
{
    'string':'stringstringstring'
}
复制代码

Data format template for 'attribute name | generation rules': 'Property Value' to generate rules determine the property value of the data generated. Generate a total of seven kinds of rules, namely:

  1. 'name|min-max': value
  2. 'name|count': value
  3. 'name|min-max.dmin-dmax': value
  4. 'name|min-max.dcount': value
  5. 'name|count.dmin-dmax': value
  6. 'name|count.dcount': value
  7. 'name|+step': value

For different data types, can be used to generate the rules are different, the data type of the attribute values ​​can be Number, Boolean, String, Object, Array, Function, Null, may not be Undefined, I will be following each data type respectively in seven generation rules, in order to observe each data type which can be used to generate rules, we want to look directly at the conclusion of the students directly pulled up to the table 1.8 in.

1.1'name|min-max': value

Before you begin you can go to my github to download the project up and running, with the project more intuitive understanding of each generation by refreshing specific rule out what kind of random data.

In mock.js file, define an array data1 holds the property value randomly generated, and define an object property value generated row1 store, and then define the analog interface, a request to initiate a request to use axios analog interface the data App.vue and displayed in the table.

const data1=[];
//数据模板'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);
//定义模拟接口只能接收post请求,定义返回的数据为data1
Mock.mock('/Get/list1','post',data1);
复制代码

| Min-max rule for string is repeated twice min-max obtained new string, it can be seen in FIG repeated four times.

For randomly generated numerical values ​​are 1-9.

For Boolean type min / (min + max) value generation probability value, max / (min + max) probability generation! Value value, where I 10% probability generation false, 90% probability generation true.

directly undefined value is ignored, undefined property name does not exist in the generated object.

For generating null value is null.

For the object, the first randomly generated value a min-max value, and select the attribute value of the object off to form a new object, if the value is greater than the number of attributes of the object, then all attributes out, Fig may Oh, see the object object attributes are all out to form a new object.

For arrays, to generate a random value in the min-max value, and then the array element value is repeated twice then combined into an array, it can be seen in FIG out random value of 6, 6 incorporates a new array of stars array.

For functions directly execute functions and a return value of the function.

1.2'name|count':value

//数据模板'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);
复制代码

The second line through the 'name | count': value generating rules

| Count rules for a string is repeated count times come new string, the figure can be seen repeated three times.

Value is generated for a value of count data.

For Boolean type (count-1) / count value of the probability of generating value, 1 / count probability generation! Value value, I have here is 66.7% probability of generating false, 33.3% probability of generating true.

directly undefined value is ignored, undefined property name does not exist in the generated object.

For generating null value is null.

For the object, the selected object attributes count out to form a new object, if the count is greater than the number of attributes of the object, then all attributes out, all can be seen in FIG Oh object attributes of the object is composed out a new object.

For an array, the array element count times repeated and combined into an array, it can be seen in FIG out random value of 3, incorporating three array to produce a new array.

For functions directly execute functions and a return value of the function.

1.3'name|min-max.dmin-dmax':value

//数据模板'name|min-max.dmin-dmax':value
let row3={
	'string|1-9.1-9':'string',
	'number|1-9.1-9':1,	//只有数值起作用
	'boolean|1-9.1-9':false,
	'undefined|1-9.1-9':undefined,
	'null|1-9.1-9':null,
	'object|1-9.1-9':{object1:'object1',object2:'object2',object3:'object3'},
	'array|1-9.1-9':['array1','array2'],
	'function|1-9.1-9':()=>'function'
};
data1.push(row3);
复制代码

The third line is obtained by 'name | min-max.dmin-dmax': value generated rule.

| Min-max.dmin-dmax rule is for strings | min-max rule.

For values, is to generate a floating-point, floating-point integer part is min-max, number of decimal places is dmin-dmax. FIG 3 generated bit integer of 2 bits decimal value 3.59.

For Boolean type is | min-max rule

directly undefined value is ignored, undefined property name does not exist in the generated object.

For generating null value is null.

For objects also | min-max rule

For arrays are | min-max rule

For functions directly execute functions and a return value of the function.

1.4'name|min-max.dcount':value

//数据模板'name|min-max.dcount':value
let row4={
	'string|1-9.3':'string',
	'number|1-9.3':1,	//只有数值起作用
	'boolean|1-9.3':false,
	'undefined|1-9.3':undefined,
	'null|1-9.3':null,
	'object|1-9.3':{object1:'object1',object2:'object2',object3:'object3'},
	'array|1-9.3':['array1','array2'],
	'function|1-9.3':()=>'function'
};
data1.push(row4);
复制代码

The fourth row is by 'name | min-max.scount': value generated rule.

| Min-max.scount rule is for strings | min-max rule.

For values, is to generate a floating-point, floating-point integer part is min-max, number of decimal places is scount. FIG 6 integer bits generated three decimal places of the value of 6.725.

For Boolean type is | min-max rule

directly undefined value is ignored, undefined property name does not exist in the generated object.

For generating null value is null.

For objects also | min-max rule

For arrays are | min-max rule

For functions directly execute functions and a return value of the function.

1.5'name|count.dmin-dmax':value

//数据模板'name|count.dmin-dmax':value
let row5={
	'string|3.1-9':'string',
	'number|3.1-9':1,	//只有数值起作用
	'boolean|3.1-9':false,
	'undefined|3.1-9':undefined,
	'null|3.1-9':null,
	'object|3.1-9':{object1:'object1',object2:'object2',object3:'object3'},
	'array|3.1-9':['array1','array2'],
	'function|3.1-9':()=>'function'
};
data1.push(row5);
复制代码

The fifth line through the 'name | count.dmin-dmax': value generating rules.

| Count.dmin-dmax rule is for strings | count rules.

For values, is to generate a floating-point, floating-point value is the integer part of the COUNT, the number of decimal places is dmin-dmax position. FIG 3 generated bit integer decimal value of six 3.035354.

For Boolean type is | count rule

directly undefined value is ignored, undefined property name does not exist in the generated object.

For generating null value is null.

For objects also | count rule

For arrays are | count rule

For functions directly execute functions and a return value of the function.

1.6'name|count.dcount':value

//数据模板'name|count.dcount':value
let row6={
	'string|3.3':'string',
	'number|3.3':1,	//只有数值起作用
	'boolean|3.3':false,
	'undefined|3.3':undefined,
	'null|3.3':null,
	'object|3.3':{object1:'object1',object2:'object2',object3:'object3'},
	'array|3.3':['array1','array2'],
	'function|3.3':()=>'function'
};
data1.push(row6);
复制代码

The sixth line through the 'name | count.dcount': value generating rules.

| Count.dcount rule is for strings | count rules.

For values, is to generate a floating-point, floating-point value is the integer part of the COUNT, the number of decimal places dcount bits. FIG 3 generated bit integer decimal values ​​of 3.425 to 3.

For Boolean type is | count rule

directly undefined value is ignored, undefined property name does not exist in the generated object.

For generating null value is null.

For objects also | count rule

For arrays are | count rule

For functions directly execute functions and a return value of the function.

1.7'name|+step':value

//数据模板'name|+step':value
let row7 = {
	'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(row7);
复制代码

The seventh line through the 'name | + step': value generating rules.

| + Step rule for strings that had no effect, directly to the string.

For the value, the initial value of a value preset value, each time re-request when a step increase numerical value, click the button below, increasing the value becomes 4 3.

For Boolean type had no effect, directly to the Boolean value returned.

directly undefined value is ignored, undefined property name does not exist in the generated object.

For generating null value is null.

For objects also had no effect, directly to the object is returned.

For a list, returns the first request to the array index value of 0, each request once again, let the subscript a STEP increase, as the click of a button, and the subscript value of 0 + 3 = 3 exceeds the maximum array subscript 1, when the index value 2 minus the length of the array until the array index value is within the maximum index of 3-2 = 1, so that the click of a button to return to the array subscript value of 1.

For functions directly execute functions and a return value of the function.

1.8 summary

String Number Boolean Undefined Null Object Array Function
| Min-max After the string is repeated twice min-max splice reveals a new string Were randomized to receive the value of min-max min / (min + max) value generation probability value, max / (min + max) probability generation! value value Current data type is invalid Return null First randomly generated value a min-max value, and select the attribute value of the object out to form a new object, if the value is greater than the number of attributes of the object, then all attributes out A first randomly generated value in the min-max value, and then the array element value is repeated twice then combined into an array Direct execution function and returns the value of the function
|count String repeated count times come new string Generating a count equal to the value (Count-1) / count value generation probability value, 1 / count probability generation! Value value Current data type is invalid Return null Select properties of the object to count out to form a new object, if the count is greater than the number of attributes of the object, then all attributes out The array elements repeated count times and then combined into an array Direct execution function and returns the value of the function
| My-max.dmin-dmax Rule | min-max same Generating a floating point, integer part of the float is min-max, number of decimal places is dmin-dmax Rule | min-max same Current data type is invalid Return null Rule | min-max same Rule | min-max same Direct execution function and returns the value of the function
|min-max.dcount Rule | min-max same Generating a floating point, integer part of the float is min-max, number of decimal places is dcount Rule | min-max same Current data type is invalid Return null Rule | min-max same Rule | min-max same Direct execution function and returns the value of the function
|count.dmin-dmax And | count the same rules Generating a floating-point, floating-point value is the integer part of COUNT, the number of decimal places bits dmin-dmax And | count the same rules Current data type is invalid Return null And | count the same rules And | count the same rules Direct execution function and returns the value of the function
|count.dcount And | count the same rules Generating a floating point number, the value of the integer part of the floating-point number COUNT is, the bit number of decimal places is dcount And | count the same rules Current data type is invalid Return null And | count the same rules And | count the same rules Direct execution function and returns the value of the function
|+step No effect, the value returned directly The initial value preset value the value of each numerical value will increase the re-request a step value once No effect, the value returned values Current data type is invalid Return null No effect, the value returned values The initial value is a preset value of the index value, each request once again, the subscript value will increase the value of a step Direct execution function and returns the value of the function

Where | min-max.dmin-dmax, | min-max.dcount, | count.dmin-dmax, | count.dcount these four rules are mainly used to type Number.

2. Use tools Rndom return value class definition analog interface

MockJS provides a set of methods that let us fast random data you want.

{
    'Boolean': Random.boolean, // 随机生成布尔类型
    'Natural': Random.natural(1, 100), // 随机生成1到100之间自然数
    'Integer': Random.integer(1, 100), // 生成1到100之间的整数
    'Float': Random.float(0, 100, 0, 5), // 生成0到100之间的浮点数,小数点后尾数为0到5位
    'Character': Random.character(), // 生成随机字符串,可加参数定义规则
    'String': Random.string(2, 10), // 生成2到10个字符之间的字符串
    'Range': Random.range(0, 10, 2), // 生成一个数组,数组元素从0开始到10结束,间隔为2
    'Date': Random.date(), // 生成一个随机日期,可加参数定义日期格式,默认yyyy-mm-dd
    'Image': Random.image(Random.size, '#02adea', 'Hello'), // Random.size表示将从size数据中任选一个数据,生成Random.size指定大小的,背景为'#02adea'的,内容为'Hello'的图片
    'Color': Random.color(), // 生成一个颜色随机值
    // 'Paragraph':Random.paragraph(2, 5), //生成2至5个句子的文本
    'Name': Random.name(), // 生成姓名
    'Url': Random.url(), // 生成url地址
    'Address': Random.province() // 生成地址
}
复制代码

The same needs to be set after the analog interface to organize data.

Mock.mock('/Get/list2', 'post', data2) ;
复制代码

To obtain an analog data and then access the interface via AJAX.

Complete code:

//mock.js
let data2 = [] // 用于接受生成数据的数组
let size = [
  '300x250', '250x250', '240x400', '336x280', 
  '180x150', '720x300', '468x60', '234x60', 
  '88x31', '120x90', '120x60', '120x240', 
  '125x125', '728x90', '160x600', '120x600', 
  '300x600'
] // 定义随机值
for(let i = 0; i < 10; i ++) { //生成10个对象放到数组中
  let template = {
    'Boolean': Random.boolean, // 可以生成基本数据类型
    'Natural': Random.natural(1, 100), // 生成1到100之间自然数
    'Integer': Random.integer(1, 100), // 生成1到100之间的整数
    'Float': Random.float(0, 100, 0, 5), // 生成0到100之间的浮点数,小数点后尾数为0到5位
    'Character': Random.character(), // 生成随机字符串,可加参数定义规则
    'String': Random.string(2, 10), // 生成2到10个字符之间的字符串
    'Range': Random.range(0, 10, 6), // 生成一个随机数组
    'Date': Random.date(), // 生成一个随机日期,可加参数定义日期格式
    'Image': Random.image(Random.size, '#02adea', 'Hello'), // Random.size表示将从size数据中任选一个数据
    'Color': Random.color(), // 生成一个颜色随机值
    'Paragraph':Random.paragraph(2, 5), //生成2至5个句子的文本
    'Name': Random.name(), // 生成姓名
    'Url': Random.url(), // 生成web地址
    'Address': Random.province() // 生成地址
  }
  data2.push(template)
}
Mock.mock('/Get/list2', 'post', data2) // 声明模拟接口

//App.vue
axios('/Get/list2').then(res => {
	this.dataShow2 = res;
});
复制代码

summary

MockJS使前后分离程度更高,同时,我认为最重要的是他使前端人员也开始思考业务。传统开发中,前端人员多是等待后端人员提供的接口及接口文档,不懂得主动梳理接口文档,使用MockJS后前端人员可以从项目整体的角度出发,能更好的参与到项目之中。

交流

如果这篇文章帮到你了,觉得不错的话来点个Star吧。 github.com/lizijie123

转载于:https://juejin.im/post/5cf726b5e51d454fbf5409bc

Guess you like

Origin blog.csdn.net/weixin_33895695/article/details/91481560