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

Problems with Vue imitating Bibibili's homepage

Engineering Structure The project is divided into...

MySQL 5.7.20 Green Edition Installation Detailed Graphic Tutorial

First, let’s understand what MySQL is? MySQL is a...

Implementation example of uploading multiple attachments in Vue

Table of contents Preface Core code File shows pa...

Nginx rush purchase current limiting configuration implementation analysis

Due to business needs, there are often rush purch...

Telnet is moved to busybox-extras in Alpine image

The telnet in the Alpine image has been moved to ...

How to Change Colors and Themes in Vim on Linux

Vim is a text editor that we use very often in Li...

Centos6.5 glibc upgrade process introduction

Table of contents Scenario Requirements glibc ver...

Introduction and examples of hidden fields in HTML

Basic syntax: <input type="hidden" na...

A Brief Analysis of Patroni in Docker Containers

Table of contents Create an image File Structure ...

MySQL permission control detailed explanation

Table of contents mysql permission control Permis...

How to solve the problem of too many open files in Linux

The cause is that the process opens a number of f...