Apidog

All-in-one Collaborative API Development Platform

API Design

API Documentation

API Designing

API Mock

API Automated Testing

Sign up for free

How to Use Mock.js in Vue.js

Start for free
Contents
Home / Applied skills / How to Use Mock.js in Vue.js

How to Use Mock.js in Vue.js

There are two ways to think about using Mock.js in your Vue project, and if you want to learn how to optimize your Vue.js front-end development process using Mock.js, then this article is a good place to start.

Mock.js is a popular JavaScript library for generating random data and intercepting Ajax requests. During the early stages of software development, backend API interfaces may not yet be implemented or may not be fully implemented. In such cases, using Mock.js can simulate the backend API for front-end developers to call, thereby avoiding the need to wait for the completion of the backend API.

There are two ways to use Mocj.js in Vue Project.

  1. Intercept Ajax on the client side. Use Mock.js to intercept Ajax requests and return randomly generated data from Mock.js.
  2. Return Mock data on the server side. Before the API is fully developed, the backend returns randomly generated data from Mock.js.

Let's take a closer look at each method.

Method 1: Intercept Ajax on the client side

Using Mock.js requires installing dependencies:

npm install mockjs --save

By using Mock.mock(url, template), you can intercept Ajax requests and return data. When an Ajax request that matches the specified URL is intercepted, the data template will be used to generate mock data, which will be returned as the response data. If no matching request is intercepted, the API call will proceed as normal.

For example, when calling the API /user/list, the user list data can be randomly returned.

import Mock from 'mockjs'
Mock.mock('/user/list', {
// The value of the "list" property is an array containing 1 to 10 elements
'list|1-10': [{
'id|+1': 1, // id starts from 1 and increments by 1
'name': '@cname', // Random Chinese name
'age|15-25': 1, // Random integer between 15 and 25
'city': '@county(true)' // Random city name
}]
})

Possible output results:

{
"list": [
{
"id": 1,
"name": "Susan Smith",
"age": 20,
"city": "New York City, New York"
},
{
"id": 2,
"name": "Emily Johnson",
"age": 24,
"city": "Los Angeles, California"
},
{
"id": 3,
"name": "Andrew Davis",
"age": 25,
"city": "Chicago, Illinois"
}
]
}

Of course, sometimes the scenarios for mocking can be more complex. It is necessary to dynamically return data based on the parameters of the API. In this case, you can use Mock.mock(url, function(options)). When a matching URL is intercepted, the function (options) will be executed and the execution result will be returned as the response data. The parameter "options" of the function refers to the Ajax options set of this request, which includes the URL, type, and body properties, as defined in the XMLHttpRequest specification.

If you want to match different methods for the same URL, you can use Mock.mock(url, method, function( options)). The second parameter is a method, and the interception will only work if both the URL and method are configured.

Method 2:  Return Mock on the Server

The server side here uses Node.js. Node.js installation is relatively easy, just download the installation package (here) and install it, which will not be discussed here.

To handle API requests on the server side, we use the lightweight web framework Express based on Node.js. To install:

$ npm install express --save

Deal with requests, and return response Mock data.

const express = require('express')
const Mock = require('mockjs')
const app = express()
const useMock = true
app.get('/user/list', (req, res) => {
if (useMock) {
const list = Mock.mock({
'list|1-10': [{
'id|+1': 1, // id starts from 1 and increments by 1
'name': '@cname', // random Chinese name
'age|15-25': 1, // random number between 15 and 25
'city': '@county(true)' // random city name
}]
})
res.send(list)
return
}
// ...res.send(normal business logic response data)
})

When calling this API, the return value is the same as Method 1. This is useful for scenarios where data needs to be dynamically returned based on the parameters of the API. Simply add logic in the route handling function of the above code. The request information can be obtained on the req object. To handle different methods for the same URL, simply add different routes. The above code only matches the GET method.

Conclusion

This article summarizes two methods for using Mock.js in a Vue project. The advantage of Method 1 is its simplicity, while the advantage of Method 2 is its flexibility and low impact on frontend code, although it requires some knowledge of Node.js.

Do you want to become a master of mocking? Apidog is a powerful API documentation management tool that makes Mock easier to use. Apidogsyntax is fully compatible with Mock.js and extends some syntax that Mock.js does not have.

button