Detailed explanation of mockjs process for recording simulation data for vue project manufacturing and development environment

Requirement: no server at all. It can achieve the same effect as connecting to the server. It does not change the interface, but only writes data

Scenario: I need to implement a function. Before, the project was directly connected with the background interface. Now I am working at home. Then I want to get a local simulation data, which can intercept get and post requests

Baidu searched a lot of data, compared them, and chose mockjs. I think it can solve most of my problems

Direct train on mock official website
Official example

this Article It's about my pain points. Let's see

What is mockjs
Generate random data to intercept Ajax requests.

Through random data, simulate various scenarios; without modifying the existing code, you can intercept Ajax requests and return simulated response data; support generating random text, numbers, Boolean values, dates, mailboxes, links, pictures, colors, etc.; support expanding more data types, support custom functions and regularities.

Very simple and convenient, non intrusive, basically covering common interface data types
mockjs can realize basic picture and text display, intercept get and post requests and render local data to the page locally
I haven't found out how to import the local pictures or videos

Solve the problem of switch between mock s and back-end interfaces, and the problem of configuration of production environment and development environment

1download mockjs:    n
pm i  mockjs --save

// The development environment can't be imported by import because it is only used in the development environment. if. When the project is started, mock will intercept http requests within its rules
if (process.env.NODE_ENV === 'development') {

3src Next new mock/mock.js file,edit mock.js file,The approximate logic file is as follows

Use and basic usage of mock.js in vue project mock JS simulates news data
On the basis of what just happened

// import mock from 'mockjs'

// mock.js
// Introducing mockjs
const Mock = require('mockjs')
// Get the mock.Random object
const Random = Mock.Random
// mock news data, including news title, content, creation time
const produceNewsData = function () {
  let newsList = []
  for (let i = 0; i < 20; i++) {
  let newNewsObject = {
    title: Random.ctitle(), // Random.ctitle (min, max) randomly generates a Chinese title with the length between 3-7 by default
    content: Random.cparagraph(), // Random.cparagraph(min, max) randomly generates a Chinese paragraph. The number of sentences in the paragraph defaults to 3-7
    createdTime: // indicates the format of the generated date string, which is yyyy MM DD by default;
     return newsList
// Request the url to return newsList
Mock.mock('/mock/news', produceNewsData) // I'll talk about the details of using this api later
// Get news list when mounting
    mounted() {
      this.axios.get('/mock/news').then(res => { // url is defined in mock.js
        console.log( // Print the response data

Operation effect:

Commodity related

const Mock = require("mockjs");
let data = Mock.mock({
    "data|100": [ //Generate 100 data arrays
            "shopId|+1": 1,//Generate commodity id, auto increment 1
            "shopMsg": "@ctitle(10)", //Generate product information with 10 Chinese characters in length
            "shopName": "@cname",//Generate commodity names, all Chinese names
            "shopTel": /^1(5|3|7|8)[0-9]{9}$/,//Generate random phone number
            "shopAddress": "@county(true)", //Randomly generated address
            "shopStar|1-5": "", //Randomly generate 1-5 stars
            "salesVolume|30-1000": 30, //Randomly generated commodity price is between 30-1000
            "shopLogo": "@Image('100x40','#c33', '#ffffff, 'little north nose'“, //Generate random picture, size / background color / font color / text message
            "food|7": [ //Seven more food s are randomly generated in each product
                    "foodName": "@cname", //The name of food
                    "foodPic": "@Image('100x40','#c33', '#ffffff, 'cute little')“,//Generate random picture, size / background color / font color / text message
                    "foodPrice|1-100": 20,//Generate 1-100 random numbers
                    "aname|14": [
                            "aname": "@cname", 
                            "aprice|30-60": 20 
Mock.mock(/goods\/goodAll/, 'post', () => { //Three parameters. First path, second request mode post/get, third callback, return value
    return data

The most important thing here is to write a data similar to the interface shown below

// commodity
let shopdata = Mock.mock({
    'status': 200,
    'msg': '',
    'data|20': [ // Generate 20 data arrays
            'id|+1': 1, // Generate commodity id, auto increment 1
            'name': '@cname', // Generate commodity names, all Chinese names
            'price|30-1000': 30, // Randomly generated commodity price is between 30-1000
            'description': '@ctitle(10)', // Generate product information with 10 Chinese characters in length
            'type|1': [ 'Wen Chuang', 'Navigation and fresh', 'Travel?' ],
            'thumbUrls': [ '@Image('40x40','#c33')', '@Image('40x40','#c33')', '@Image('40x40','#c33')', '@Image('40x40','#c33')' ],
            'isfree|1': [0, 1] // 0 charge 1 free
// Three parameters. First path, second request mode post/get, third callback, return value
Mock.mock('/api/news/list', 'get', () => { return shopdata })

//Arbitrarily.vue file
// Get news list when mounting
    mounted() {
      this.axios.get('/api/item/list').then(res => { // url is defined in mock.js
        console.log( // Print the response data

Output result

mockjs syntax learning

Array random one out of three

  "array|1": [


  "array": "CMD"

I want to update this data to the page and display it

Problem occurred: the above mounted data can be printed out, the bottom one can't

I wrote the simulation data of the game in the morning. I wanted to write the simulation data of the game and video and display it on the page
And then I kept reporting it wrong

I think this error may be related to the passing value of props, because no data can be obtained, so the error is reported. So I gave up this transition to display shop data, because this page is not finished yet, so it's easier to change

Then I tried to write the interface into created


I guess I'm right, because mockjs doesn't know the parameters passed by, so it doesn't intercept

Problems encountered
When using Mock.mock('/ api/item/list', 'get', () = > {return shopdata}), it only intercepts requests with url equal to / api/item/list, while for requests with parameters, such as / api/item/list?type = creation, because it cannot be intercepted if it is not equal to / api/item/list.

Then solve it How does Mockjs intercept GET requests with parameters Problem

Mock.mock( rurl, rtype, function( options ) )
Record 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 execution result is returned as the response data.

Indicates the URL to be intercepted, which can be a URL string or a regular URL. For example / \ / domain\/list\.json /, '/ domain / list. JSON'.

Represents the type of Ajax request that needs to be intercepted. For example, GET, POST, PUT, DELETE, etc.

Represents a data template, which can be an object or a string. For example, {'data|1-10': [{}]}, '@ EMAIL'.

Represents the function used to generate response data.

 The Ajax option set that points to this request contains three attributes: url, type and body

Thus we can see that
In mockjs, the method of Mock.mock() will accept three parameters. The first parameter is the intercepted interface, the second parameter is the intercepted request mode, and the third parameter is the option set of this request

The URL to be intercepted can be a URL string or a regular URL

Mock.mock(RegExp(url + ".*"), "get", mockData);
And then I tried, and I found that this couldn't be achieved
Mock.mock(RegExp('/api/item/list' + '.*'), 'get', () => { return shopdata })
Alternative method
Mock.mock(/\/api\/item\/list[\s\S]*?/, 'get', () => { return shopdata })

Something's coming out. The explanation works
Now the question is, how can pictures not come out

I suspect it's because the letter is wrong. It shouldn't be capitalized

Finally, I found that the field without the picture was not written

Look, it's out

The WebSocket connection error has not been resolved

Original: !== 11
this.loginForm && && !== 11

//Original userInfo !== undefined && userInfo.length > 10
userInfo && userInfo.length > 10

Now the data simulated by mockjs has come to an end. The remaining problems are as follows:

We also need to find some video, e-book, music, game resources and other http links

Reference documents:
vue projects use. env files to configure global environment variables
Detailed explanation of vue-cli3 configuration development and test environment
How to use Mockjs in the Vue project to simulate the data returned by the interface and realize the independent development of front and back end separation
Control the use of mock in development environment and disable it in production environment in vue

183 original articles published, 62 praised, 160000 visitors+
Private letter follow

Tags: mockjs Vue axios JSON

Posted on Mon, 16 Mar 2020 01:11:51 -0700 by sebnewyork