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

How to use jsx syntax correctly in vue

Table of contents Preface Virtual DOM What is Vir...

MYSQL database basics - Join operation principle

Join uses the Nested-Loop Join algorithm. There a...

Nginx server adds Systemd custom service process analysis

1. Take nginx as an example Nginx installed using...

JavaScript implements circular carousel

This article shares the specific code of JavaScri...

Analysis of the solution to Nginx Session sharing problem

This article mainly introduces the solution to th...

JS implements simple addition and subtraction of shopping cart effects

This article example shares the specific code of ...

js realizes 3D sound effects through audioContext

This article shares the specific code of js to ac...

Implementation of vscode custom vue template

Use the vscode editor to create a vue template, s...

Getting Started Tutorial for Beginners: Domain Name Resolution and Binding

So after registering a domain name and purchasing...

Vue implements infinite loading waterfall flow

This article example shares the specific code of ...

Summary of MySQL stored procedure permission issues

MySQL stored procedures, yes, look like very rare...

MySQL 8.0 New Features: Hash Join

The MySQL development team officially released th...

Install .NET 6.0 in CentOS system using cloud server

.NET SDK Download Link https://dotnet.microsoft.c...