The Mock. Introduction of js

I believe that you have just participated in the internship or work of the front-end friends will encounter such a problem: when we have completed the production of the static page of the project, at this time, we need to provide interface for us to request and display data, but the back-end students say that the interface has not been completed. Is all we got to do now is wait?

Some students may say: you can first write dead data in the local display, such as the interface out, and then delete them. As I am a non-professional rookie who just participated in the internship, I also did this at the beginning (dog head), but this undoubtedly increased a lot of unnecessary repetitive operations, and after the interface came out, I still need to spend energy to delete them, which seriously reduced the development efficiency.

So, this is a good time to consider the front end building the Web Server itself to simulate fake data, followed by mockJS, the main character of this article. You can use it to generate random data and block Ajax requests.

Mock.js official website: mockjs.com/

The mockJS website shows its features below:

Start & initialization

Here I use MockJS in conjunction with a Vue scaffolding project.

# use mockjs to generate random data NPM install mockjs --save-devCopy the code

You can then create a mock folder in SRC and create a new index.js file in SRC, where you can write the code to simulate the interface data.

Import mock from 'mockjs' // Mock interface data specific code...Copy the code

Import the mock in main.js

Import Vue from 'Vue' import App from './ app.vue '// import mock Import './mock/index.js' Vue.config.productionTip = false new Vue({ render:h => h(App), }).$mount('#app')Copy the code

This completes the installation and initialization of MockJS! Let’s look at the syntax.

Grammar specification

The syntax specification for mock.js consists of two parts:

  1. Data template definition specification(Data Template Definition, DTD)
  2. Data placeholder definition specification(Data Placeholder Definition, DPD)

1. Data template definition specification DTD

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

/ / the name attribute name/value rule / / / generate rules attribute value 'name |' rule: the valueCopy the code
  • Use a vertical line between the attribute name and the generation rule|Space.
  • The generation rule is optional.
  • There are seven formats for generating rules:
    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
  • The meaning of the generation rule depends on the type of the attribute value.
  • Property value can contain@ placeholder.
  • The property value also specifies the initial value and type of the final value.

Example:

(1) The attribute value is a String

  1. 'name|min-max': string

    Generate a string by repeating string more than min and less than Max.

  2. 'name|count': string

    Generate a string by repeating string times equal to count.

(2) The attribute value is Number

  1. 'name|+1': number

    Attribute value automatically increments by 1, starting with number.

  2. 'name|min-max': number

    Generates an integer greater than or equal to min and less than or equal to Max. The value of the attribute number is used only to determine the type.

  3. 'name|min-max.dmin-dmax': number

    Generates a floating point number with the integer part greater than or equal to min and the integer part less than or equal to Max and the decimal part reserved from dmin to dmax bits.

Mock. Mock ({' number1 | 1-100.1-10 ": 1, 'number2 | 123.1-10' : 1, 'number3 |' 123.3:1, 'number4 | 123.10' : }) // => {"number1": 12.92, "number2": 123.51, "number3": 123.777, "number4": 123.1231091814}Copy the code

(3) The attribute value is Boolean

  1. 'name|1': boolean

    Generate a random Boolean value with a 1/2 chance of true and 1/2 chance of false.

  2. 'name|min-max': value

    Generates a random Boolean value with a probability of min/(min + Max) with a value of! The probability of value is Max over min plus Max.

(4) The attribute value is the Object

  1. 'name|count': object

    Select count randomly from the attribute value object.

  2. 'name|min-max': object

    Randomly select min to Max attributes from the attribute value object.

(5) The property value is Array Array

  1. 'name|1': array

    One element is randomly selected from array as the final value.

  2. 'name|+1': array

    Select one element from array as the final value.

  3. 'name|min-max': array

    Generates a new array by repeating the property value array more than min and less than Max.

  4. 'name|count': array

    Generates a new array by repeating the property value array, count times.

(6) The attribute value is Function

  1. 'name': function

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

(7) The attribute value is the regular expression RegExp

  1. 'name': regexp

    Generate a string that matches the regular expression regexp in reverse. String used to generate custom formatting.

Mock. Mock ({' regexp1: / [a-z] [a-z] / [0-9], 'regexp2: / \ w \ w \ s \ s \ \ d/d,' regexp3: / \ d {5, 10}}) / / = > {" regexp1 ": "pJ7", "regexp2": "F)\fp1G", "regexp3": "561659409" }Copy the code

2. Data placeholder definition specification DPD

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

The format of the placeholders is:

@ placeholder @ placeholder (parameter [, parameter])Copy the code

Note:

  1. with@To identify the string that follows as a placeholder.
  2. The placeholder refers toMock.RandomMethod in.
  3. throughMock.Random.extend()To extend custom placeholders.
  4. Placeholders can also refer to properties in the data template.
  5. Placeholders refer to attributes in the data template in preference.
  6. Placeholders support both relative and absolute paths.
Mock.mock({
    name: {
        first: '@FIRST',
        middle: '@FIRST',
        last: '@LAST',
        full: '@first @middle @last'
    }
})
// =>
{
    "name": {
        "first": "Charles",
        "middle": "Brenda",
        "last": "Lopez",
        "full": "Charles Brenda Lopez"
    }
}
Copy the code

Methods in Mock.Random correspond to the @ placeholder 1-1 of the data template, and you can extend methods for Mock.Random if needed, and then reference them in the data template via the @ extension method. Such as:

Random.extend({ constellation: Function (date) {var constellations = [' Aries ', 'Gemini ',' Cancer ', 'Leo ',' Libra ', 'Scorpio ',' Sagittarius ', 'Aquarius '] return this.pick(constellations)}}) random.constellation () // => "Aquarius" Mock. Mock (' @constellation ') // => "Scorpio" Mock. Mock ({constellation: '@constellation'}) // => {constellation: "Sagittarius"}Copy the code

3.Mock.mock

Invoke the Mock. Mock (rurl? , rtype? , the template | function (options)) to generate simulated data

(1) Mock.mock( template )

Generate simulated data from the data template.

(2) Mock.mock( rurl, template )

Record the data template. When an Ajax request matching an RURL is intercepted, mock data is generated from the data template and returned as response data.

(3) Mock.mock( rurl, function( options ) )

Records the function used to generate the response data. When an Ajax request matching an RURL is intercepted, the function(options) is executed and the result is returned as response data.

(4) Mock.mock( rurl, rtype, template )

Record the data template. When Ajax requests matching rURL and RType are intercepted, mock data is generated from the data template and returned as response data.

(5) Mock.mock( rurl, rtype, function( options ) )

Records the function used to generate the response data. When an Ajax request matching rURL and RType is intercepted, the function(options) is executed and the result is returned as response data.

  • rurl

Optional. Indicates the URL to be intercepted. It can be a URL string or A URL re. For example /\/domain\/list.json/ and ‘/domian/list.json’.

  • rtype

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

  • template

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

  • function(options)

Optional. Represents the function used to generate the response data.

  • options

The set of Ajax options pointing to this request contains the URL, Type, and body attributes

Examples of common basic syntax

1. Generate a string

  • Generates a string of specified degrees
Const data = Mock. Mock ({" string | 3 ", "aa" / / generated aaaaaa "})Copy the code
  • Generates a string of the specified range length
Const data = Mock. Mock ({" string | 1-8 ":" a "/ / 1-8 random length of" a "})Copy the code

2. Generate text

  • Generates a random string
const data = Mock.mock({
    "string": "@cword"  
}) 
Copy the code

Note: at the end of the @ symbol begins with c generally means Chinese, for example, cword at the top represents a random Chinese character, if it is word, it is a random English word.

  • Generates the specified length and range
Const data = Mock. Mock ({string: "@cword(1)" STR: "@cword(10,15)"})Copy the code

3. Generate headings and sentences

  • Generate headings and sentences
const data = Mock.mock({
    title: "@ctitle"
    sentence: "@csentence"
})
Copy the code
  • Generates headings and sentences of specified length
const data = Mock.mock({
    title: "@ctitle(8)"
    sentence: "@csentence(50)"
})
Copy the code
  • Generates headings and sentences for the specified range
Const data = Mock. Mock ({title: "@ctitle(5,8)" sentence: "@csentence(50,100)"})Copy the code

4. Generate paragraphs

  • Randomly generated paragraph
const data = Mock.mock({
  content: "@cparagraph()"
})
Copy the code

5. Generate numbers

  • Generate the specified number
const data = Mock.mock({
    "number|80": 1
})
Copy the code
  • Generate range number
const data = Mock.mock({
    "number|1-99": 1
})
Copy the code

6. Generate the self-added ID

  • Randomly generated identifier
Const data = Mock. Mock ({id: "@increment(1)" // increment(1)})Copy the code

7. Generate name – address – ID card

  • Random generation name – address – ID card
Const data = Mock. Mock ({name: "@cname()" idCard: "@id()" address: "@city(true)" // @city with true})Copy the code

8. Generate random images

  • Generate image: @image (size? , background? , foreground? , format? , the text?
  • Size: indicates the image size
[' 300 * 250 ', '250 * 250', '240 * 400', '336 * 280' 180 * 150 ', '720 * 300', '468 * 60', '234 * 60' '388 * 31', '250 * 250', '240 * 400', '120 * 40' '125 * 125', '250 * 250', '240 * 400', '336 * 280]Copy the code
  • Background: The background color of an image
  • Foreground: Foreground of the picture
  • Format: Indicates the image format
  • Text: picture text

9. Generation time

  • @Date
  • Time: @date(YYYY-MM-DD hh: MM :ss)

Specifies the parameters returned by the array

  • Specified length: ‘date | 5’
  • Specified range: ‘data | 5-10’
const data = Mock.mock({
'list|50-99':[
        {
            name:'@cname'
            address:'@city(true)'
            id:'@increment()'
        }	
    ]
})
Copy the code

For more examples, see mockjs.com/examples.ht…

Below, I’ll demonstrate the use of MockJS with two small demos that combine Vue’s add, delete, modify, and check functions.

Concrete Example 1

First, we import and mount Axios in main.js so that we can request interface data via $HTTP in each component.

Import Vue from 'Vue' import App from './ app.vue '// import mock import './mock/index.js' import axios from 'axios' // Prototype.$HTTP = axios vue.config. productionTip = false new Vue({render:h => h(App),}).$mount('# App ')Copy the code

Next, we’ll write mock data to index.js in the mock folder we created earlier

Import Mock from 'mockjs' import {Random} from 'mockjs' import {Random} from 'mockjs' create custom Mock function random.extend ({// Custom function name: The function function fruit: The function () {const arr = [' durian ', 'jackfruit, coconut,' apple ', 'pineapple', Mock. Mock ('/ API /goodslist', 'get', {status: 200, message: 'Get! ', 'data | 5-10' : [{id: '@ increment (1)', / / on the id value / / 'id | + 1:0, / / it is also in a simulated a id values since the growth of name: Price: '@natural(2, 10)', // count: '@natural(100, 999)', img: Mock. Mock ('/ API/addGoods ', 'post', Function (option) {console.log(option) // If you need to mock on the returned object, Mock. Mock return Mock. Mock ({status: 200, message: '@ cword (2, 5)'})}) / / according to Id for commodity information Mock. The Mock (/ \ \ / API/getgoods /, 'get', Function (option) {console.log(option) // Through the regular.exec() function, Const res = /\/ API \/ getGoods /(\d+)/.exec(option.url) // Can also split the string to get id // const urlId = Option.url.split ('/')[3] return Mock. Mock ({data: {id: res[1] -0, // id: urlId, // @fruit() '@fruit()', price: 2, count: 199, img: '@dataimage (78x78)'}, status: 200, message: '})})Copy the code

Then send the corresponding request in the component where we need to request the interface data

<template> <div id="app"> < button@click ="getGoodsList"> </button> < button@click ="addGoods" </button> </div> </template> <script> export default {methods: Async getGoodsList() {const {data: $http.get('/ API /goodslist') console.log(res)}, Async addGoods() {const {data: res} = await this.$http.post('/ API/addGoods ', {name: }) console.log(res)}, // Async getGoodsById(Id) {const {data: res } = await this.$http.get(`/api/getgoods/${id}`) console.log(res) } } } </script>Copy the code

In specific development, there will be more code to request interface data, and when all the code for requesting interface data is placed under index.js, the file will become bloated and difficult to manage and distinguish. In fact, we can modularize different types of requests like Vuex’s module separation.

For example, split the goods-related simulation data into goods.js:

Mock ('/ API /goodslist', 'get', {... Mock ('/ API/addGoods ', 'post', function(option) {... Mock. Mock (/\/ API \/ getGoods /, 'get', function(option) {... })Copy the code

Split the code for your custom mock function into extends. Js:

Import {Random} from 'mockjs' import {Random} from 'mockjs' import {Random} from 'mockjs' import {Random} from 'mockjs' import {Random} from 'mockjs' The function () {const arr = [' durian ', 'jackfruit, coconut,' apple ', 'pineapple', 'Buddha'] return this. Pick (arr)}})Copy the code

If there are other modules, the data can also be placed in different files, such as the user module code in user.js, the shopping cart module code in cart.js, and so on.

Finally, import it centrally in the entry file index.js

// Import extension function import './extends' // Import the goods module import './goods' // import the user module user.js // import the shopping cart module cart.jsCopy the code

The final file directory under the mock folder looks like this:

Concrete Example 2

In fact, instance 2 is basically similar to instance 1. It is also the operation of adding, deleting, changing and searching lists, but on the basis of instance 1, it has added the function of paging, and the parameters of the request data are different, and the way of deleting and adding is slightly different. Here I will not divide modules, and directly write all in index.js

import Mock from "mockjs"; / / by deconstruction assignment simulation news list data const. {newsList} = Mock Mock ({" newsList | 75 ": [{id:" @ increment ", the title: "@ ctitle ()", the content: "@ cparagraph (5, 10)," img_url: "@ image (' 50 * 50 ', '# FF83FA', '# FCFCFC', 'the PNG', 'mono)", add_time: "@date(yyyy-MM-dd hh:mm:ss)", }, ], }); console.log(newsList); / / to encapsulate a function to get the query parameter from the url / / such as retrieved from https://juejin.cn/user/4433690702123534?id=1&name=rocky? Var getQuery = (url, name) => {console.log(url, name); Const index = url.indexof ("?"); ); if (index ! == -1) {// intercept? ['id=1', 'name= Rocky '] const queryStrArr = url.substr(index + 1).split("&"); for (var i = 0; i < queryStrArr.length; [id, 1],[name, rocky] const itemArr = queryStrArr[I].split("="); console.log(itemArr); If (itemArr[0] === name) {return itemArr[1]; } } } return null; }; // Get the news list data // because the specific URL form is similar to/API /get/news? Mock (/\/ API \/get\/news/, "get", (options) => {// get the page-related parameter pageIndex, pagesize const pageindex = getQuery(options.url, "pageindex"); const pagesize = getQuery(options.url, "pagesize"); console.log(pageindex); console.log(pagesize); // Get the starting position of the data, Const start = (pageindex -1) * pagesize; // pageIndex :1 pagesize:10 const start = (pageindex -1) * pagesize; const end = pagesize * pageindex; const totalPage = Math.ceil(newsList.length / pagesize); const list = pageindex > totalPage ? [] : newsList.slice(start, end); Return {status: 200, message: "get the list successfully ", list: list, total: totalPage,}; }); Mock ("/ API /add/news", "post", (options) => {const body = json.parse (options.body); console.log(body); newsList.push( Mock.mock({ id: "@increment", title: body.title, content: body.content, img_url: "@image('50*50','#FF83FA','#FCFCFC','png','mono')", add_time: "@date(yyyy-MM-dd hh:mm:ss)", }) ); Return {status: 200, message: "added successfully ", list: newsList, total: NewsList. Length,}}) // define delete news mock. Mock ("/ API /delete/news", "post", (options) => {console.log(options); const body = JSON.parse(options.body); console.log(body); const index = newsList.findIndex((item) => { return item.id === body.id; }); newsList.splice(index, 1); console.log(index); Return {status: 200, message: "Delete successfully ", list: newsList, total: newsList. Length,}}) console.log(Mock)Copy the code

In the component that specifically requests interface data:

<template> <div> <div class="add"> <input type="text" V-model ="title" placeholder=" placeholder "/> <input type="text" V-model ="content" placeholder=" input "/> <button @click="add"> </button> </div> <div class="news_list"> <table> <tr v-for="item in list" :key="item.id"> <td><img :src="item.img_url" alt="" /></td> <td>{{ item.title }}</td> <td>{{ Item. The content}} < / td > < td > {{item. Add_time}} < / td > < td > < button class = "remove" @ click = "remove (item. Id)" > delete < / button > < / td > </tr> </table> </div> <div class="pages"> < button@click ="prevPage">  </div> </div> </template> <script> import axios from "axios"; export default { data() { return { title: "", content: "", list: [], pageindex: 1, title: "", content: "", }; }, created() { this.getNewsList(); }, methods: {/ / add news data add () {/ / if (this. Title. The trim () = = = "" | | this. The trim () = = =" ") / / return alert (" please add those headlines and content "); // console.log(this.title, this.content); axios.post("/api/add/news", { title: this.title, content: this.content, }).then((res) => { console.log(res); }); }, // get newslist () {axios.get("/ API /get/news", {params: {pageIndex: this.pageIndex, pagesize: 10, }, }).then((res) => { console.log(res); this.list = res.data.list; }); }, nextPage() { this.pageindex++; this.getNewsList(); }, prevPage() { this.pageindex--; this.getNewsList(); }, // delete news remove(id) {// console.log(id); axios.post("/api/delete/news", {id}) .then((res) => { console.log(res); }); } } } </script>Copy the code

reference

Mock. Js’s official website: mockjs.com/ B station Mock relevant tutorial: www.bilibili.com/video/BV1v7… www.bilibili.com/video/BV1Tt…