Front end Mockjs data simulation

Posted by jamesm87 on Fri, 18 Feb 2022 09:27:31 +0100

1. Install mockjs (the complete code of this case is at the bottom)

Install mock through the instruction npm install mockjs,

Then create a mock folder under src folder, and then create an index JS file

 

Then in main Introducing mock into JS file

After that, you can find the index. In the mock file Simulated data in JS file

1. First, we need the index under mock Introducing mock into JS file

import Mock from "mockjs";

2. Next, here we simulate a news list data, which is an array with a length of 75, and each array element is an object,

Those who don't know much about mock data can check it on the official website of mockjs

const { newsList } = Mock.mock({
    "newsList|75": [{
        id: "@increment",//Indicates self increment
        title: "@ctitle()",//Chinese title
        content: "@cparagraph(5,10)",//5-10 sentences representing Chinese paragraphs
        img_url: "@image('50*50','#FF83FA','#FCFC ',' PNG ',' mono ') ", / / indicates a picture
        add_time: "@date(yyyy-MM-dd hh:mm:ss)",//Indicates the date
    }, ],
});

 3. We continue to define an interface in this file

var getQuery = (url, name) => {
    console.log(url, name);
    const index = url.indexOf("?");
    if (index !== -1) {
        const queryStrArr = url.substr(index + 1).split("&");
        for (var i = 0; i < queryStrArr.length; i++) {
            const itemArr = queryStrArr[i].split("=");
            console.log(itemArr);
            if (itemArr[0] === name) {
                return itemArr[1];
            }
        }
    }
    return null;
};

// Define the data to get the news list
// /api/get/news?pageinde1&pagesize=10
Mock.mock(/\/api\/get\/news/, "get", (options) => {
    // Get the transfer parameters pageindex, pagesize
    console.log(options)
    const pageindex = getQuery(options.url, "pageindex");
    const pagesize = getQuery(options.url, "pagesize");
    console.log(pageindex);
    console.log(pagesize);
    const start = (pageindex - 1) * pagesize;
    const end = pagesize * pageindex;
    const totalPage = Math.ceil(newsList.length / pagesize);

    //  pageindex:1 pagesize:10 return 0-9 pieces of data 2-10 - (10-19) 3-10 (20-29)
    // Start position of data: (pageindex-1) * pagesize end position: pageindex*pagesize
    const list = pageindex > totalPage ? [] : newsList.slice(start, end);
    return {
        status: 200,
        message: "Get news list successfully",
        list: list,
        total: totalPage,
    };
});


Mock. There are three parameters in mock(),

  1. The first parameter is the interface api of the request, the second parameter is the request method get/post, and the third parameter is a function,

After configuring according to the above code, we simulate a data interface, and we can request the simulated data from the interface

axios.get("/api/get/news", {
          params: {
            pageindex: this.pageindex,
            pagesize: 10,
          },
        })
        .then((res) => {
          console.log(res);
          this.list = res.data.list;
        });

Note that this is a get request and parameters are passed. We are configuring mock When mock(), the first parameter must be in the form of regular expression,

The above code has been used as an example, but we passed mock How can the mock () simulated interface get the parameters carried by the request?

At this point, we need to print options,

Here I will directly explain that options is an object, and the body and url attributes are used to receive parameters, so we need to deal with it

options.body and options url

, the parameters carried by the get request are listed in {options URL, is a very long string, internal? After the character is the parameter carried,

Therefore, we need to review options URL to get the parameters, so how do we deal with it?

var getQuery = (url, name) => {
    console.log(url, name);
    const index = url.indexOf("?");
    if (index !== -1) {
        const queryStrArr = url.substr(index + 1).split("&");
        for (var i = 0; i < queryStrArr.length; i++) {
            const itemArr = queryStrArr[i].split("=");
            console.log(itemArr);
            if (itemArr[0] === name) {
                return itemArr[1];
            }
        }
    }
    return null;
};

This function allows you to set options URL as the first parameter, and pass in the desired parameter name as the second parameter

const pageindex = getQuery(options.url, "pageindex");
    const pagesize = getQuery(options.url, "pagesize");

You can find options Parameters of URL

Finally, the complete request interface can be defined

// Define the data to get the news list
// /api/get/news?pageinde1&pagesize=10
Mock.mock(/\/api\/get\/news/, "get", (options) => {
    // Get the transfer parameters pageindex, pagesize
    console.log(options)
    const pageindex = getQuery(options.url, "pageindex");
    const pagesize = getQuery(options.url, "pagesize");
    console.log(pageindex);
    console.log(pagesize);
    const start = (pageindex - 1) * pagesize;
    const end = pagesize * pageindex;
    const totalPage = Math.ceil(newsList.length / pagesize);

    //  pageindex:1 pagesize:10 return 0-9 pieces of data 2-10 - (10-19) 3-10 (20-29)
    // Start position of data: (pageindex-1) * pagesize end position: pageindex*pagesize
    const list = pageindex > totalPage ? [] : newsList.slice(start, end);
    return {
        status: 200,
        message: "Get news list successfully",
        list: list,
        total: totalPage,
    };
});

2.options. The parameters in the body are the parameters carried by the post request

Is a string, we need to pass JSON Parse (options. Body) is converted into an object. In this case, options carries the title and content parameters. The code is as follows

// Define data for adding news
Mock.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,
    };
});

 

Then we can send a request to add news data through the following code

axios.post("/api/add/news", {
          title: this.title,
          content: this.content,
        })
        .then((res) => {
          console.log(res);
        });

This case is the complete index in mock js

import Mock from "mockjs";

const { newsList } = Mock.mock({
    "newsList|75": [{
        id: "@increment",
        title: "@ctitle()",
        content: "@cparagraph(5,10)",
        img_url: "@image('50*50','#FF83FA','#FCFCFC','png','mono')",
        add_time: "@date(yyyy-MM-dd hh:mm:ss)",
    }, ],
});

console.log(newsList);
var getQuery = (url, name) => {
    console.log(url, name);
    const index = url.indexOf("?");
    if (index !== -1) {
        const queryStrArr = url.substr(index + 1).split("&");
        for (var i = 0; i < queryStrArr.length; i++) {
            const itemArr = queryStrArr[i].split("=");
            console.log(itemArr);
            if (itemArr[0] === name) {
                return itemArr[1];
            }
        }
    }
    return null;
};

// Define the data to get the news list
// /api/get/news?pageinde1&pagesize=10
Mock.mock(/\/api\/get\/news/, "get", (options) => {
    console.log(options);
    // Get the transfer parameters pageindex, pagesize
    const pageindex = getQuery(options.url, "pageindex");
    const pagesize = getQuery(options.url, "pagesize");
    console.log(pageindex);
    console.log(pagesize);
    const start = (pageindex - 1) * pagesize;
    const end = pagesize * pageindex;
    const totalPage = Math.ceil(newsList.length / pagesize);

    //  pageindex:1 pagesize:10 return 0-9 pieces of data 2-10 - (10-19) 3-10 (20-29)
    // Start position of data: (pageindex-1) * pagesize end position: pageindex*pagesize
    const list = pageindex > totalPage ? [] : newsList.slice(start, end);
    return {
        status: 200,
        message: "Get news list successfully",
        list: list,
        total: totalPage,
    };
});

// Define data for adding news
Mock.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: "Added successfully",
        list: newsList,
        total: newsList.length,
    };
});
console.log(Mock);

The code is as follows

Topics: Front-end Vue.js