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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft