How do you implement a data mock natively? You can also use online tools such as EasyMock to implement mock data, but if you want stability, build a local environment. Here I show you how to implement mock data using vue-CLI’s own functionality.

Initialize the project

(1) Use VUe-CLI to initialize

vue create mock-demo
Copy the code

Use the default values

(2) Create a configuration file

Create the vue.config.js configuration file in the project root directory. As follows:

const bodyParser = require("body-parser");
const isProduction = process.env.NODE_ENV === "production";

let feMock;
if(! isProduction) { feMock =require("./mockApi");
}
module.exports = {
  publicPath: isProduction ? ". /. /" : "".pages: {
    index: {
      entry: "src/main.js".template: "public/index.html".filename: "index.html"}},devServer: {
    before: app= > {
        // Key code
      app.use(bodyParser.json());
      app.use(bodyParser.urlencoded({ extended: true }));
      if(! isProduction) { feMock(app); }}}};Copy the code

The mock function implemented by Webpack-dev-server is utilized, and axios and Body-Parser are installed in order to implement interface requests.

npm i axios body-parser -S
Copy the code

Apis for writing mocks

(1) Create a folder mockApi in the root directory of the project and create index.js

const feMock = app= > {
  app.get("/mock/api/news".function(req, res) {
    res.json({
      name: "tom"
    });
  });
};
module.exports=feMock;
Copy the code

(2) Create an API folder in SRC and create the index.js file

const prefix = "/mock";
export default {
  methods: {
    _testMock() {
      return this.$http.get(`${prefix}/api/news`); }}};Copy the code

The request path here must be the same as the path of the previous mock data. After the back-end interface is written, modify the prefix interface in this file.

Components use

(1) Use it in app.vue

<script> import api from "./api"; export default { name: "App", mixins: [api], mounted() { this.testMock(); this.testMock1(); this.testPostMock(); }, methods: { testMock() { this._testMock() .then(res => { console.log(res); }) .catch(err => { console.log(err); }); }}}; </script>Copy the code

After starting the project normally, the request will be visible in the browser network, and the initial functionality will be implemented.

To optimize the

(1) What happens if multiple people write multiple mock files in your project?

(2) Can I scan a specific directory to load mock files? Could there be a unified external entry, where everyone just writes their own mock files and doesn’t have to modify the exit?

The solution

(1) Create a mockList folder under mockApi folder, and then write everyone’s mock interface there. The following is an example:

Create a new test.js in mockList

function testMock(app) {
  app.get("/mock/api/news".function(req, res) {
    res.json({
      name: "tom"
    });
  });
}

function testPostMock(app) {
  app.post("/mock/api/news".function(req, res) {
    console.log(req.body);
    setTimeout(function() {
      res.json({
        code: 0.data: "success".desc: ""
      });
    }, 500);
  });
}
module.exports = [testMock, testPostMock];

Copy the code

Create a new test1.js in mockList

function testMock1(app) {
  app.get("/mock/api/news1".function(req, res) {
    res.json({
      name: "jack"
    });
  });
}
module.exports = [testMock1];
Copy the code

(2) Modify the mockApi/index.js file

const fs = require("fs");
const path = __dirname;
const files = fs.readdirSync(path + "/mockList");
const mockList = [];
files.forEach(function(filename) {
  let model = require(path + "/mockList/"+ filename); mockList.push(... model); });function handleMock(app) {
  mockList.forEach(func= > {
    func(app);
  });
}

module.exports = handleMock;

Copy the code

The introduction of FS automatically reads files in the specified directory, so that once configured, others can write their own mock interfaces without having to modify the external file.

The sample code directory structure is as follows: