当前位置:网站首页>Let the front-end siege division develop independently from the back-end: Mock.js
Let the front-end siege division develop independently from the back-end: Mock.js
2020-11-06 01:17:00 【:::::::】
One .Mock.js What is it? ?
At present, most of the company's projects are based on the separation of front end and back end , The development of the back-end interface and the front-end personnel are carried out at the same time . Then there will be a problem at this time , Before a page needs to be rendered with a large amount of data , The back-end developer's interface may not be finished , As the front end, we have no way to get data . therefore The front-end engineer needs to simulate the data provided by the back-end personnel according to the interface document , In this way, the development of the page .
This is the time , Mock.js The function of , In case of large amount of data , We don't have to write data one by one , Just fill in the data format according to the interface document , Mock.js It can automatically generate a large number of simulation data on demand . And Mock.js Provides a large number of data types , Including text , Numbers , Boolean value , date , mailbox , link , picture , Color, etc. .
This article is a brief introduction to Mock.js Provided grammar , And I'd like to introduce how I usually use Mock.js To make it easier to develop .
Two . Download and import Mock.js
1. download Mock.js
Mock.js Provides a variety of download methods , In this paper, the most commonly used npm give an example , Just type... On the command line npm install mockjs
Can finish Mock.js The download .
2. introduce Mock.js
Mock.js Exposed a global Mock
object , We just need to put Mock
Object is introduced into the file , call Mock The method of object can be
- CommonJS How to introduce
//CommonJS introduce let Mock = require('mockjs) // call Mock.mock() Methods simulate data let data = Mock.mock({ 'list|1-10': [{ 'id|+1': 1 }] }); console.log(data);
- ES6 How to introduce
//ES6 How to introduce import Mock from 'mockjs' let data = Mock.mock({ 'list|1-10': [{ 'id|+1': 1 }] }); console.log(data);
3、 ... and .Mock.js The simple grammar of
Mock
The object provides 4 A way , Namely Mock.mock()
, Mock.setup()
, Mock.valid
, Mock.toJSONSchema()
, A tool library Mock.Random
. One of the things we often use is Mock.mock()
and Mock.Random
.
1. Mock.js The specification of
The second part introduces Mock.js The following parts of the code can reflect Mock.js Grammatical norms of
'list|1-10': [{ 'id|+1': 1 }]
The above code is called a data template , Used to tell Mock.js What kind of data is generated , Each attribute in the data template consists of three parts : Property name , Generate rules , Property value :
-
list
Is the attribute name in the data template ; -
1-10
For generating rules ( It means that the generation is the least 1 individual , most 10 Duplicate data ) -
[{'id|+1': 1}]
It's property value , Property names and generation rules can be nested in property values .
For specific generation rules, see : https://github.com/nuysoft/Mo...
2. Mock.mock()
Mock.mock()
Method is used to generate simulation data based on the data template , I often use the following two ways of transmitting reference :
-
Mock.mock(template)
: According to the data templatetemplate
Generate simulation data
let data = Mock.mock({ data: { 'products|10-20': [{ name: ' mobile phone ', price: 1000 }] } }) console.log(data);
-
Mock.mock(url, template)
: The address of the interception request isurl
Of ajax request , And according to the data templatetemplate
Generate simulation data
let data = Mock.mock('api/products' , { data: { 'products|10-20': [{ name: ' mobile phone ', price: 1000 }] } }) // Use jquery Ajax Send a request $.ajax({ url: 'api/products', type: 'GET', success: function(res) { console.log(res); } })
3. Mock.Random
Mock.Random yes Mock.js Provide a tool class , Used to generate several commonly used data .
- Generating Boolean values
// Use @ Placeholder way let data = Mock.mock({ data: { boolean: '@boolean' } }) console.log(data); // Use Mock.Random How to call a function let data = Mock.mock({ data: { boolean: Mock.Random.boolean() } }) console.log(data);
- Generated on
let data = Mock.mock({ data: { date: Mock.Random.date('yyyy-MM-dd') } }) console.log(data);
Mock.js Support rich date format customization : https://github.com/nuysoft/Mo...
- Generate pictures
let data = Mock.mock({ data: { // Used to generate highly customized image addresses imgURL: Mock.Random.image() } }) console.log(data);
- Generate name
let data = Mock.mock({ data: { // Generate an English name name: Mock.Random.name(), // Generate a Chinese name chineseName: Mock.Random.cname() } }) console.log(data);
more Mock.Random Data provided by the tool library : https://github.com/nuysoft/Mo...
Four . stay Vue Project use Mock.js
Take the data simulating a login interface as an example :
1. Write a single mockData.js
File as the generating file of virtual data .
//mockData.js import Mock from 'mockjs' let Random = Mock.Random; // User login information let userInfo = Mock.mock({ data: { responseCode: 200, responseMessage: 'success', userMessage: { email: Random.email(), 'id|1-10': 1, realName: Random.cname(), roleCodes: 'admin', username: Random.first() } } }) let mockData = { userInfo: userInfo } export default mockData;
2. Use vuex To control whether to use mock.js The data of
// src/store/index.js import Vue from 'vue' import Vuex from 'vuex' import mutations from './mutations' import actions from './actions' Vue.use(Vuex); const state = { // Using simulated data , It's just for development , If it's not development time , Please be sure to set to false useMock: true } export default new Vuex.Store({ state, mutations, actions })
3. stay Login.vue To implement the request login method
//Login.vue import mockData from '../utils/mockData.js' exwport default { ... methods: { fetchUserInfo() { // If vuex in userMock by true if (this.$store.state.useMock) { // Use a delayer to simulate asynchrony window.setTimeout(() => { let res = mockData.userInfo; // Business logic }, 1000); return; } // If vuex in userMock by false this.$axios.post('api/login', params).then(res => { // Business logic }); } } }
As can be seen in the Login.vue Of fetchUserInfo()
In the method , If userMock
by true
, What will be used is mock.js
Simulation data in ; If useMock
by false
, Using the Ajax Requested data . The good thing about that is , You just need to vuex I'd like to make a change in , You can control the use of Ajax Request data , Or use analog data . In this way, during the joint debugging with the background , You can switch data freely !
Reference link
- Mock.js Official website : http://mockjs.com/
Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .
版权声明
本文为[:::::::]所创,转载请带上原文链接,感谢
边栏推荐
- Using Es5 to realize the class of ES6
- 你的财务报告该换个高级的套路了——财务分析驾驶舱
- How to select the evaluation index of classification model
- A debate on whether flv should support hevc
- 有关PDF417条码码制的结构介绍
- In depth understanding of the construction of Intelligent Recommendation System
- Synchronous configuration from git to consult with git 2consul
- 哇,ElasticSearch多字段权重排序居然可以这么玩
- The practice of the architecture of Internet public opinion system
- PHP应用对接Justswap专用开发包【JustSwap.PHP】
猜你喜欢
助力金融科技创新发展,ATFX走在行业最前列
Calculation script for time series data
How long does it take you to work out an object-oriented programming interview question from Ali school?
业内首发车道级导航背后——详解高精定位技术演进与场景应用
(1) ASP.NET Introduction to core3.1 Ocelot
有关PDF417条码码制的结构介绍
Technical director, to just graduated programmers a word - do a good job in small things, can achieve great things
采购供应商系统是什么?采购供应商管理平台解决方案
C++和C++程序员快要被市场淘汰了
中国提出的AI方法影响越来越大,天大等从大量文献中挖掘AI发展规律
随机推荐
Group count - word length
如何在Windows Server 2012及更高版本中將域控制器降級
一时技痒,撸了个动态线程池,源码放Github了
Using consult to realize service discovery: instance ID customization
drf JWT認證模組與自定製
做外包真的很难,身为外包的我也无奈叹息。
技術總監,送給剛畢業的程式設計師們一句話——做好小事,才能成就大事
全球疫情加速互联网企业转型,区块链会是解药吗?
“颜值经济”的野望:华熙生物净利率六连降,收购案遭上交所问询
Real time data synchronization scheme based on Flink SQL CDC
使用NLP和ML来提取和构造Web数据
【新閣教育】窮學上位機系列——搭建STEP7模擬環境
從小公司進入大廠,我都做對了哪些事?
Every day we say we need to do performance optimization. What are we optimizing?
Details of dapr implementing distributed stateful service
TRON智能钱包PHP开发包【零TRX归集】
Aprelu: cross border application, adaptive relu | IEEE tie 2020 for machine fault detection
Programmer introspection checklist
Skywalking series blog 2-skywalking using
DRF JWT authentication module and self customization