Vue uses mockjs to generate simulated data case details

Vue uses mockjs to generate simulated data case details

Install mockjs in your project

Execute the following installation command in the project directory

npm install mockjs --save

The basic process of using mockjs in Vue project

After the installation is complete, create a new mock.js in the project's src/utils directory (you can define the directory and file name yourself) to generate mock data.

// Import mockjs
const Mock = require('mockjs')

// Generate simulation data const test = function() {
    return Mock.mock({
        // The value of the attribute list is an array containing 1 to 10 elements 'list|1-10': [{
            // The attribute id is a self-incrementing number, starting at 1 and increasing by 1 each time
            'id|+1': 1,
            // Generate random data through placeholder 'name': '@name',
            'age': '@natural(18, 100)',
            'email': '@email'
        }]
    });
}

// Map the access URL
// This means that when Ajax requests the /mock/test path, the test function will be mapped and executed Mock.mock('/mock/test', test)

In the project src/api directory, create MockSrv.js to respond to Ajax requests.

import axios from 'axios'
import mock from '@/utils/mock'

export default {
    testMock() {
        return axios.get('/mock/test')
    }
}

Request mock data generated by Mock in the component.

<script>
import MockSrv from '@/api/MockSrv'

export default {
    name: 'App',
    mounted() {
        MockSrv.testMock().then(function(resp) {
            console.log("Mock:", resp.data);
        });
    }
}
</script>

Execution Results

insert image description here

Mock Syntax Specification

Data Template Definition (DTD)

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

// Attribute name
// Generate rule
// attribute value
'name|rule': value

Data Placeholder Definition (DPD)

A placeholder simply takes up a place in the attribute value string and does not appear in the final attribute value.
The format of the placeholder is:

@placeholder@placeholder(parameters[, parameters])

Mock.mock({
    name: {
        first: '@FIRST',
        middle: '@FIRST',
        last: '@LAST',
        full: '@first @middle @last'
    }
})

Mock.mock()

Generate simulated data based on data template
Mock.mock(rurl?, rtype?, template | function(options))

  • rurl is optional and indicates the URL to be intercepted. It can be a URL string or a URL regular expression.
  • rtype is optional and indicates the type of Ajax request that needs to be intercepted. For example, GET, POST, PUT, DELETE, etc.
  • template is optional, indicating a data template, which can be an object or a string
  • function(options) optional, indicating the function used to generate response data
    • options refers to the Ajax options set for this request, which contains three attributes: url, type and body

Mock.Random()

Mock.Random is a tool class used to generate various random data.
The Mock.Random method is called a "placeholder" in the data template, and the writing format is @placeholder(parameter[, parameter]).

var Random = Mock.Random
Random.email()
// => "[email protected]"
Mock.mock('@email')
// => "[email protected]"
Mock.mock( { email: '@email' } )
// => { email: "[email protected]" }

The methods in Mock.Random correspond one-to-one to the @ placeholders in the data template. If necessary, you can also extend the methods of Mock.Random and then reference them in the data template through @ extension methods.

This is the end of this article about Vue's use of mockjs to generate simulated data cases. For more relevant Vue's use of mockjs to generate simulated data content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Using mockjs code examples in Vue
  • Detailed explanation of how to use mockjs to simulate data in vue-cli project
  • Detailed explanation of using Mockjs in vue-cli project
  • Example of using mockjs to simulate backend data in vue+vuecli+webpack
  • Detailed explanation of using mockjs in vue-cli project (request data to delete data)

<<:  How to block IP and IP range in Nginx

>>:  What are the differences between sql and mysql

Recommend

MySQL database green version installation tutorial to solve system error 1067

What is the difference between the green version ...

MySQL slow query pt-query-digest analysis of slow query log

1. Introduction pt-query-digest is a tool for ana...

Summary of MySQL date and time functions (MySQL 5.X)

1. MySQL gets the current date and time function ...

Example of using setInterval function in React

This article is based on the Windows 10 system en...

Detailed explanation of Nginx configuration file

The main configuration file of Nginx is nginx.con...

Correct modification steps for Docker's default network segment

background A colleague is working on his security...

JavaScript implements front-end countdown effect

This article shares the specific code of JavaScri...

How to install mysql5.6 in docker under ubuntu

1. Install mysql5.6 docker run mysql:5.6 Wait unt...

Solution to the CSS height collapse problem

1. High degree of collapse In the document flow, ...

Methods of adaptive web design (good access experience on mobile phones)

1. Add the viewport tag to the HTML header. At th...