Do you know how to use mock in vue project?

Do you know how to use mock in vue project?

Mock.js is a mock data generator designed to help front-end developers develop independently from the back-end and to help write unit tests. The following simulation functions are provided:

  • Generate simulated data based on data template
  • Simulate Ajax requests, generate and return simulated data
  • Generate mock data based on HTML template

first step:

npm install mockjs // Install mockjs
npm install axios

The second step is to make relevant configurations in request.js. The request.js code is as follows:

import axios from 'axios'
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-urlencoded'
const http = axios.create()
 http.defaults.timeout = 3000
 http.interceptors.request.use(config => { // Request interceptor configuration // optional // do sth
    return config
}, error => {
    console.log(error)
    return Promise.reject(error)
})
 http.interceptors.response.use(response => { // Response interceptor configuration // Optional // do something
    return response
}, error => {
    console.log(error)
    return Promise.reject(error)
})
 export function fetch(url, params) { // Encapsulate axios's post request return new Promise((resolve, reject) => { // Promise usage, please refer to axios.post(url, params).then(response => {
            resolve(response.data) // promise related}).catch(error => {
            reject(error) // promise related})
    })
}
 export default { // Expose the htto_mock method, which is the method used in the following pages http_mock(url, params) {
        return fetch(url, params)
    }
}

The third step is to perform relevant configuration in mock.js. The mock.js code is as follows:

import Mock from 'mockjs'
 const Random = Mock.Random
 var listData = function() {
    let _data = {
        status: 200,
        message: 'success',
        data: {
            total: 100,
            'rows|10': [{
            id: '@guid',
            name: '@cname',
            'age|20-30': 23,
            'job|1': ['Front-end engineer', 'Back-end engineer', 'UI engineer', 'Requirements engineer']
            }]
        }
    }
    return { _data }
}
// url is the request address to be intercepted request method request data (rules) (the api here will be intercepted by mockjs)
Mock.mock('http://route.showapi.com/60-27', 'post', listData())
 

The fourth step is to import mock.js into main.js

import mock from '@/http/mock'

Step 5: Use it in the page

import request from '@/http/request'
 export default {
    name: "FirstPage",
    created() {
        this.getData()
    },
    methods: {
        getData() {
             // Pretend to use http_mock to send a request (mock automatically intercepts the request and generates data)
   // The first parameter here needs to be consistent with the first parameter in Mock.mock() console.log('Request started')
            request.http_mock('http://route.showapi.com/60-27','api_id=63114&api_sign=3847b0').then(response => {
            console.log(response._data)
            })
       },
    }
}

The effect is as follows:

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • The use and basic usage of mock.js in vue project
  • Complete steps to use mock.js in Vue project
  • Detailed explanation of how to use mock data in local development of vue-cli
  • How to control mock in development environment and disable it in production environment in Vue

<<:  CSS method of clearing float and BFC

>>:  Detailed explanation of downloading, installing and using nginx server

Recommend

User experience analysis of facebook dating website design

<br />Related article: Analysis of Facebook&...

20 excellent foreign web page color matching cases sharing

This article collects 20 excellent web page color ...

Solution to "No input file specified" in nginx+php

Today, the error "No input file specified&qu...

Detailed tutorial on deploying Apollo custom environment with docker-compose

Table of contents What is the Apollo Configuratio...

Vue implements countdown function

This article example shares the specific code of ...

Solve the error during connect exception in Docker

When you first start using Docker, you will inevi...

Vue template compilation details

Table of contents 1. parse 1.1 Rules for intercep...

Implementation of CSS child element selection parent element

Usually a CSS selector selects from top to bottom...

How to mark the source and origin of CSS3 citations

I am almost going moldy staying at home due to th...

Detailed explanation of scp and sftp commands under Linux

Table of contents Preface 1. scp usage 2. Use sft...

Detailed explanation of the MySQL MVCC mechanism principle

Table of contents What is MVCC Mysql lock and tra...

7 Best VSCode Extensions for Vue Developers

Adding the right VS Code extension to Visual Stud...

js to achieve simple accordion effect

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