1. Build a test project


1.1 Creating a Project

vue create mock-demo
Copy the code

1.2 Installation Dependencies

// Use axios to send ajax
cnpm install axios --save
// Use mockJS to generate random numbers
cnpm install mockjs --save-dev
// Use json5 to resolve the problem that json files cannot be annotated
cnpm install json5 --save-dev
Copy the code

2. Mockjs use

Create a mock folder under the root of your project and create a testmock. js file to test the use of mocks.

The use of 2.1 testMock. Js

Introducing mocks in testMokejs files:

// Introduce the MockJS module to use mock
const mock = require('mockjs')
// For simple use, get a random ID
let id = mock.mock('@id')
// Randomly generate an object
let boj = mock.mock({
  id: "@id()".// Get the random ID of the object
  username: "@cname()".// Randomly generate Chinese names
  date: "@date()".// Randomly generate the date
  avatar: "@image('200x200','red','#fff','avatar')".// Generate random images
  description: "paragraph()".// Randomly generate a description
  ip: "@ip()".// Randomly generate IP addresses
  email: "@email()".// Randomly generate an email address
})
Copy the code


3. The use of json5

3.1 Introduce the JSON5 library to parse the Json5 format

Create testJson5.js under the Mock folder

// To create a userinfo.json5 file, enter the JSON data format
// Json5 can be used normally.
const JSON5 = require('json5')
// The advantage of using Json5 is that you can simplify operations such as annotations
// Read the file to get the path
const fs = require('fs')
const path = require('path')
// Change the data in JSON from a string to an object
const json5 = require('json5')

let json = fs.readFileSync(path.join(__dirname,'./userinfo.json5'),'utf-8')
var obj = json5.parse(json);
console.log(obj);
// This is a json file, but the data is a string
// Save the string as a JSON object.
Copy the code

4. Mock in vue.cli

Configure the condition in the vue.config.js file under the root directory

module.exports = {
  devServer: {
    before: require('./mock/index.js')/ / into a mock/index. Js}}Copy the code

Create the index.js file under the mock folder

// Return a function
module.exports = function(app){
  // Listen for HTTP requests
  app.get('/user/userinfo'.function(rep,res){
    // Read the mock Data json file every time you respond to a request
    The getJsonFile method defines how to read json files and parse them into data objects
    let json = getJsonFile('./userInfo.json5');
    // Pass json to the mock. In the mock method, the generated data is returned to the browserres.json(mock.mock(json)); })}Copy the code

The Mounted hook function in the helloWorld. vue file sends the Ajax request.

import axios from 'axios'/ / import library
axios.get('/user/userinfo').then(res= > {
  console.log(res);
})
.catch(err= > {
  console.log(err);
})
Copy the code

In normal development, mocks are used to simulate data when the back-end interface is not written, so how do you stop using mocks when the back-end interface is already written? In index.js:

// Return a function
module.exports = function(app){
  
  //process.env.MOCK is used only when MOCK equals true, otherwise use backend interface data
  if(process.env.MOCK == 'true') {// The environment variable is in the root of the project directory
  // Create.env.development with MOCK = true
  // If the back-end interface is already successful, MOCK = false can be set so that the back-end interface will apply
  / / disable the mock
  
    
       // Listen for HTTP requests
      app.get('/user/userinfo'.function(rep,res){
        // Read the mock Data json file every time you respond to a request
        The getJsonFile method defines how to read json files and parse them into data objects
        let json = getJsonFile('./userInfo.json5');
        // Pass json to the mock. In the mock method, the generated data is returned to the browserres.json(mock.mock(json)); }}})Copy the code

The environment variable is created in the root directory of the project directory. Env.development file. MOCK = true is set to MOCK = false if the back-end interface has already been successful.