当前位置:网站首页>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 :
-
listIs the attribute name in the data template ; -
1-10For 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 templatetemplateGenerate 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 isurlOf ajax request , And according to the data templatetemplateGenerate 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 .
版权声明
本文为[:::::::]所创,转载请带上原文链接,感谢
边栏推荐
- [performance optimization] Nani? Memory overflow again?! It's time to sum up the wave!!
- Details of dapr implementing distributed stateful service
- How to demote a domain controller in Windows Server 2012 and later
- Real time data synchronization scheme based on Flink SQL CDC
- A debate on whether flv should support hevc
- 采购供应商系统是什么?采购供应商管理平台解决方案
- 谁说Cat不能做链路跟踪的,给我站出来
- Polkadot series (2) -- detailed explanation of mixed consensus
- 熬夜总结了报表自动化、数据可视化和挖掘的要点,和你想的不一样
- 【效能優化】納尼?記憶體又溢位了?!是時候總結一波了!!
猜你喜欢

從小公司進入大廠,我都做對了哪些事?

华为云“四个可靠”的方法论

Use of vuepress

Kitty中的动态线程池支持Nacos,Apollo多配置中心了

Technical director, to just graduated programmers a word - do a good job in small things, can achieve great things

Python自动化测试学习哪些知识?

drf JWT認證模組與自定製

Swagger 3.0 天天刷屏,真的香嗎?

怎么理解Python迭代器与生成器?

How to demote a domain controller in Windows Server 2012 and later
随机推荐
Basic principle and application of iptables
网络安全工程师演示:原来***是这样获取你的计算机管理员权限的!【维持】
Cos start source code and creator
GUI 引擎评价指标
How long does it take you to work out an object-oriented programming interview question from Ali school?
Tool class under JUC package, its name is locksupport! Did you make it?
The practice of the architecture of Internet public opinion system
Grouping operation aligned with specified datum
IPFS/Filecoin合法性:保护个人隐私不被泄露
钻石标准--Diamond Standard
Cocos Creator 原始碼解讀:引擎啟動與主迴圈
Sort the array in ascending order according to the frequency
網路程式設計NIO:BIO和NIO
In depth understanding of the construction of Intelligent Recommendation System
X Window System介紹
Skywalking series blog 1 - install stand-alone skywalking
【效能優化】納尼?記憶體又溢位了?!是時候總結一波了!!
加速「全民直播」洪流,如何攻克延时、卡顿、高并发难题?
50 + open source projects are officially assembled, and millions of developers are voting
恕我直言,我也是才知道ElasticSearch条件更新是这么玩的