当前位置:网站首页>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 .
版权声明
本文为[:::::::]所创,转载请带上原文链接,感谢
边栏推荐
猜你喜欢
随机推荐
嘗試從零開始構建我的商城 (二) :使用JWT保護我們的資訊保安,完善Swagger配置
连肝三个通宵,JVM77道高频面试题详细分析,就这?
业内首发车道级导航背后——详解高精定位技术演进与场景应用
一时技痒,撸了个动态线程池,源码放Github了
Jmeter——ForEach Controller&Loop Controller
EOS创始人BM: UE,UBI,URI有什么区别?
50 + open source projects are officially assembled, and millions of developers are voting
ThreadLocal原理大解析
数字城市响应相关国家政策大力发展数字孪生平台的建设
(1) ASP.NET Introduction to core3.1 Ocelot
Top 10 best big data analysis tools in 2020
至联云解析:IPFS/Filecoin挖矿为什么这么难?
Asp.Net Core學習筆記:入門篇
《Google軟體測試之道》 第一章google軟體測試介紹
怎么理解Python迭代器与生成器?
This article will introduce you to jest unit test
Azure Data Factory(三)整合 Azure Devops 實現CI/CD
03_ Detailed explanation and test of installation and configuration of Ubuntu Samba
CCR炒币机器人:“比特币”数字货币的大佬,你不得不了解的知识
中国提出的AI方法影响越来越大,天大等从大量文献中挖掘AI发展规律





