Using mockjs in Vue cli project (basic use and global configuration use)

reference resources: vue+mockjs simulation data to achieve the separation of front and back end development (Github-Demo All codes can be viewed), Mockjs ,Axios

In many cases, the data required by the front-end and the back-end interface will not be developed synchronously in the development process of projects separated from the front-end and the back-end. At this time, before the interface docking, mockjs can be used to define the simulation data

The requests in the vue project are usually made by using Axios. One of the characteristics of Axios is that it will automatically intercept requests. This afternoon, I also referred to many articles and almost completed the demo

For the use of axios, please refer to the official website.

After the scaffold is set up

npm install mockjs // install mockjs
npm install axios // Install axios

I. basic use (used in a separate page)

< button @ Click = "GetData" > generate data < / button > 
import Mock from 'mockjs' // node Method introduction (CommonJS)

export default {
  name: 'HelloWorld',
  data () {
    return {
      mockData: [] // Generate data
    }
  },
  methods: {
    getRandom () {
      this.mockData = Mock.mock({ //Generate data rules
        'list|1-10': [{
          'id|+1': 1
        }]
      })
      document.body.innerHTML += '<pre>' + JSON.stringify(this.mockData, null, 4) + '</pre>' // Show to page
    }
  }

II. Global configuration (introduced in main.js)

Project directory composition (src folder under myapp)

First look at http---request.js

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
    // do sth
    return config
}, error => {
    console.log(error)
    return Promise.reject(error)
})

http.interceptors.response.use(response => { // Response interceptor configuration
    // do something
    return response
}, error => {
    console.log(error)
    return Promise.reject(error)
})

export function fetch(url, params) { // encapsulation axios Of post request
    return new Promise((resolve, reject) => { // promise usage,Self access
        axios.post(url, params).then(response => {
            resolve(response.data) // promise relevant
        }).catch(error => {
            reject(error) // promise relevant
        })
    })
}

export default { // Expose htto_mock Method, which is used in the following pages
    http_mock(url, params) {
        return fetch(url, params)
    }
}

Then configure mock(mock.js file)

import Mock from 'mockjs'

const Random = Mock.Random

var listData = function() {
    let _data = []
    for (let i = 0; i < 20; i++) {
    let newList = { // Refer to mockjs official website for detailed rules
      title: Random.csentence(5, 30), //  Random.csentence( min, max )
      imgSrc: Random.dataImage('200x160', 'This is the text in the picture'), // Random.dataImage( size, text ) Generate picture( base64 Bit data format)
      author_name: Random.cname(), // Random.cname() Randomly generate Chinese name
      date: Random.date() + ' ' + Random.time() // Random.date()Indicates the format of the generated date string,Default is yyyy-MM-dd;Random.time() Returns a random time string
    }
      _data.push(newList)
  }
  return {_data: _data}
}
// url Request data (rule) for request address request mode to be blocked (here api Will be mockjs Intercept)
Mock.mock('http://route.showapi.com/60-27', 'post', listData)

In main.js, you only need to import it

import mock from './mock'

Finally, it's the use of the page

Introduce request.js

import request from '@/http/request'

mock intercepts and generates. When I use created, it is generated directly. Event triggering is the same

created () {
    this.getData()
},
method: {
    getData() { // Pretend to send a request using HTTP ﹐ mock (﹐ manual ﹐ mock) (mock automatically intercepts the request and generates data)
         request.http_mock('http://route.showapi.com/60-27','api_id=63114&api_sign=3847b0').then(response => {
            console.log(response._data)
} } }

Last data:

After the completion of other pages can be used under the introduction, after the background interface docking, mockjs directly cancel the use of ok.

Tags: Javascript axios mockjs Vue github

Posted on Mon, 16 Dec 2019 13:58:18 -0500 by waq2062