当前位置:网站首页>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 .
版权声明
本文为[:::::::]所创,转载请带上原文链接,感谢
边栏推荐
- JetCache埋点的骚操作,不服不行啊
- Technical director, to just graduated programmers a word - do a good job in small things, can achieve great things
- 选择站群服务器的有哪些标准呢?
- How long does it take you to work out an object-oriented programming interview question from Ali school?
- Vue 3 responsive Foundation
- 向北京集结!OpenI/O 2020启智开发者大会进入倒计时
- PHPSHE 短信插件说明
- 3分钟读懂Wi-Fi 6于Wi-Fi 5的优势
- 人工智能学什么课程?它将替代人类工作?
- After brushing leetcode's linked list topic, I found a secret!
猜你喜欢

采购供应商系统是什么?采购供应商管理平台解决方案

助力金融科技创新发展,ATFX走在行业最前列

Want to do read-write separation, give you some small experience

中国提出的AI方法影响越来越大,天大等从大量文献中挖掘AI发展规律

Tool class under JUC package, its name is locksupport! Did you make it?

自然语言处理之命名实体识别-tanfordcorenlp-NER(一)

(1)ASP.NET Core3.1 Ocelot介紹

至联云解析:IPFS/Filecoin挖矿为什么这么难?

ipfs正舵者Filecoin落地正当时 FIL币价格破千来了

神经网络简史
随机推荐
华为云“四个可靠”的方法论
X Window System介紹
选择站群服务器的有哪些标准呢?
Kitty中的动态线程池支持Nacos,Apollo多配置中心了
(1) ASP.NET Introduction to core3.1 Ocelot
如何将数据变成资产?吸引数据科学家
03_ Detailed explanation and test of installation and configuration of Ubuntu Samba
html
熬夜总结了报表自动化、数据可视化和挖掘的要点,和你想的不一样
做外包真的很难,身为外包的我也无奈叹息。
哇,ElasticSearch多字段权重排序居然可以这么玩
WeihanLi.Npoi 1.11.0/1.12.0 Release Notes
深度揭祕垃圾回收底層,這次讓你徹底弄懂她
快快使用ModelArts,零基础小白也能玩转AI!
Can't be asked again! Reentrantlock source code, drawing a look together!
Query意图识别分析
Polkadot series (2) -- detailed explanation of mixed consensus
C language 100 question set 004 - statistics of the number of people of all ages
(1)ASP.NET Core3.1 Ocelot介紹
谁说Cat不能做链路跟踪的,给我站出来