search
HomeWeb Front-endJS TutorialHow to use Mockjs in vue-cli project

How to use Mockjs in vue-cli project

May 29, 2018 pm 05:45 PM
javascriptvue-cliNow

This time I will show you how to use Mockjs in the vue-cli project, and what are the precautions for using Mockjs in the vue-cli project. The following is a practical case, let's take a look.

Background

Front-end In the early jQuery era, front-end functions and back-end engineering were basically combined. The typical one was common The webapp directory under the maven project contains various front-end static resource files.

At this time, we always encounter these problems:

  1. Boss, the interface document has not been output yet, so I can’t do a lot of work!

  2. Backend guy, have you written the interface? I want to test it!

  3. There is not enough time for testing, and the version is about to be released. Did I watch the sun rise tomorrow today?

All kinds of things, just one sentence: Labor and management, don’t count on you anymore!

After node appeared, or to be precise, after the separation of front-end and back-end, the front-end urgently needed a mechanism that no longer needed to rely on back-end interface development. After several years of development, many big names have conducted research in this area.

Now we can finally implement real simulation testing. For example, today’s protagonist mockjs

Usage details

1. First create a mock folder in the src directory and define the mock main file index.js. Define the interception routing configuration in this file;

/**
 * 定义本地测试接口,最好与正式接口一致,避免联调阶段修改工作量
 */
// 引入mockjs
import Mock from 'mockjs';
// 引入模板函数类
import record from './presc-record-api';
Mock.setup({
 timeout: 800, // 设置延迟响应,模拟向后端请求数据
});
// Mock.mock( url, post/get , 返回的数据);
Mock.mock(/\/api\/healthPlat\/getRecipe\/\w*\/\w*/, 'get', record.getRecipe);

2. Define the template function class in the specified file, example:

// 获取 mock.Random 对象
// 引入mockjs
import { Random } from 'mockjs';
import Utils from './Utils';
function getRecipe(req) {
 // mock一组数据
 const data = [];
 for (let i = 0; i <p style="text-align: left;">3. Introduce mock/index.js into main.js File;</p><pre class="brush:php;toolbar:false">// 引入mock文件
import './mock/index'; // mock 方式,正式发布时,注释掉该处即可

The next step is to configure your mock routing and template functions. Have Fun!

pitfalls

Here I will introduce the pitfalls when using Mockjs in vue-cli:

1. The request path contains variables, what should I do?

Coders who have used router know that we often have to deal with routes that contain parameters in the address. At this time, we only need to use regular expression in Mockjs to match the path. Completed, example:

Copy code The code is as follows:

Mock.mock(/\/api\/healthPlat\/getRecipeDetail\/\w*\/\w */, 'get', record.getRecipeDetail);

That is, we only use regular character sets in variables to match our variables.

2. Why don’t I see my request in the network in the console?

When I first started testing, I checked the network and didn’t see the request, which was strange! Just ask yourself a few questions:

  1. Why introduce mockjs related configuration files in main.js entry file?

  2. Aren’t entry files compiled in webpack and then executed in the browser?

  3. The console did not intercept the request, that means it did not intercept the request sent to the server, right?

With these questions, I read the source code and documentation and found:

  1. In the source code, first check whether the request is defined in Mockjs. There is Then intercept, and then use its mock request object MockXMLHttpRequest to respond, that is, no XHR request is sent at this time;

  2. Otherwise, use the local standard XHR object to make the request. At this time, you can make the request in the console network See Request Information

Therefore, introducing the relevant configuration files of mockjs in the main.js entry file means adding the simulation of Mockjs to the front-end code. method, it will be executed in the browser instead of actually sending a request, but we can print it to the console to view it.

Netizens commented that you can use mockjs in the server. At this time, it is a real request. You can view the request information in the console. I have not practiced the corresponding practice here. If you are interested, you can refer to mock-server:

3. Using template syntax, the returned data contains rules "|rules", causing parsing or value acquisition to fail. What should I do?

刚开始的时候,我按照文档上说的模板语法进行配置,如:

看到属性 code 居然带着规则一起返回了,我说我请求为啥没有解析成功啊,原来 res.code 一直是 undefined ,这是坑啊。
查看源码和可以搜到的网上示例发现:没有使用模板规则的现象,而是使用 mockjs 提供的内置函数来实现,如 .id() .cname() 等等方法。

于是我将mock相关文件中 code 定义改成下面这样:

function setRes(req, options) {
 window.console.log(req.url);
 const { code = Random.int(0, 5) >= 1 ? 1 : 0, message, data = {}, totalCount = 100 } = options;
 const result = {
  code,
  message: message || ['失败', '错误', '异常'][Random.integer(0, 2)],
  data,
  totalCount,
 };
 window.console.log(result);
 return result;
}

刚开始的时候属性code是这样定义的—— 'code|1', true, ,后来改成了 code = Random.boolean(),发现生成 false 的概览太高了,不适合我们真实的场景。

想到我们只需要增加 code 为 1 的概率,于是本人使用 Random.int(0, 5) 随机生成一个整数,当这个整数大于等于1,我们将 code 设置为 1 ,其他情况为 0 。

也就是说从概率上将,成功的概率为 0.8,失败的概率为 0.2,基本符合我们测试要求,哈哈,机智不^

4.模拟异步请求的过程,发现请求好像是瞬间完成,loading效果没生效

刚开始的时候,没有设置延迟响应,每次请求都好像是瞬间完成的,没有一步操作的那种等待感,没有看到loading罩层出现。
自己debug时,loading罩层是有的,于是想到:请求没有被延迟,而是被同步执行了。

想到lodash.debounce 函数有延迟网络请求、稀释事件、延迟执行的效果,于是将模板函数用 debounce 包裹起来,如下:

复制代码 代码如下:

Mock.mock('/api/healthPlat/chronicdisease', 'get', debounce(record.chronicdisease, 600));

结果出现有意思的事情:当请求比较频繁,在延迟时间内,本次请求得到的响应数据是上次请求的结果。这显然不是我们希望看到的,而且我们一般是用 debounce 的来稀释请求的,用在请求发送之后显然违背了我们的初衷。

翻阅 mockjs 文档,发现作者已经考虑了这个事情。哎,辛苦忙活了大半天,还是要好好看文档啊。具体如下:

Mock.setup({
 timeout: 800, // 设置延迟响应,模拟向后端请求数据
});

5. Mock 无法拦截带参数的 get 请求

刚开始时,发现设置的有些 get 请求总是请求不到 mock 的数据,而有些 get 请求能得到 mock 的数据,post 则不存在这样的问题。非常郁闷!

仔细 debug 时发现:get 请求带参数时失败,找不到路径;get 请求不带参数成功,路径没找到,获取到 mock 的数据;post 路径正确找到,成功得到 mock 数据。

这时突然意思到:get 请求的路径默认后面会加上参数,因此和设置的路径没有匹配上,导致路径没找到,请求失败。
于是本人将路径改成正则表达式,就好了。如:

// 刚开始字符串路径,带参数的 get 请求匹配失败
Mock.mock('/api/healthPlat/renewCancel', 'get', manage.renewCancel);

改成下面这样就好了:

// 正则表达式路径,带参数的 get 请求匹配成功
Mock.mock(/\/api\/healthPlat\/renewCancel/, 'get', manage.renewCancel);

但是实际开发过程中,发现上述正则表达式不够完备,如后续我们又另一个路径 /api/healthPlat/renewCancelAddr 也会匹配上述地址,这不是我们希望有的。

此时我们只需改进下正则表达式即可:

// 正则表达式路径,带参数的 get 请求匹配成功
Mock.mock(/\/api\/healthPlat\/renewCancel(|\?\S*)$/, 'get', manage.renewCancel);

即只有路径为 /api/healthPlat/renewCancel 的 get 请求才会匹配上述规则。

最后建议:get 请求都用正则表达式书写路径;post 字符串和正则都行;

总结

mock虽然存在以上所涉及的局限和问题,不过对于日常自测联调还是很有益处,个人觉得主要还是简单可行。当然本文所述方式,不仅仅局限在 vue-cli 中,其他框架中亦可按此法进行配置。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

如何修改npm全局安装模式路径

How to use WebPack to configure vue multi-page

The above is the detailed content of How to use Mockjs in vue-cli project. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),