当前位置:网站首页>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 .
版权声明
本文为[:::::::]所创,转载请带上原文链接,感谢
边栏推荐
- [C#] (原創)一步一步教你自定義控制元件——04,ProgressBar(進度條)
- drf JWT認證模組與自定製
- 嘘!异步事件这样用真的好么?
- 数字城市响应相关国家政策大力发展数字孪生平台的建设
- Skywalking series blog 2-skywalking using
- 幽默:黑客式编程其实类似机器学习!
- WeihanLi.Npoi 1.11.0/1.12.0 Release Notes
- 关于Kubernetes 与 OAM 构建统一、标准化的应用管理平台知识!(附网盘链接)
- Skywalking series blog 1 - install stand-alone skywalking
- Jmeter——ForEach Controller&Loop Controller
猜你喜欢

drf JWT認證模組與自定製

钻石标准--Diamond Standard

2018中国云厂商TOP5:阿里云、腾讯云、AWS、电信、联通 ...

hadoop 命令总结

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

The difference between Es5 class and ES6 class

Filecoin最新动态 完成重大升级 已实现四大项目进展!

加速「全民直播」洪流,如何攻克延时、卡顿、高并发难题?

Grouping operation aligned with specified datum

(1) ASP.NET Introduction to core3.1 Ocelot
随机推荐
CCR炒币机器人:“比特币”数字货币的大佬,你不得不了解的知识
嘘!异步事件这样用真的好么?
中国提出的AI方法影响越来越大,天大等从大量文献中挖掘AI发展规律
hadoop 命令总结
条码生成软件如何隐藏部分条码文字
技術總監,送給剛畢業的程式設計師們一句話——做好小事,才能成就大事
从海外进军中国,Rancher要执容器云市场牛耳 | 爱分析调研
X Window System介紹
微服務 - 如何解決鏈路追蹤問題
Filecoin的经济模型与未来价值是如何支撑FIL币价格破千的
Wiremock: a powerful tool for API testing
Subordination judgment in structured data
速看!互联网、电商离线大数据分析最佳实践!(附网盘链接)
Jmeter——ForEach Controller&Loop Controller
Kitty中的动态线程池支持Nacos,Apollo多配置中心了
Technical director, to just graduated programmers a word - do a good job in small things, can achieve great things
你的财务报告该换个高级的套路了——财务分析驾驶舱
自然语言处理之命名实体识别-tanfordcorenlp-NER(一)
Flink on paasta: yelp's new stream processing platform running on kubernetes
快快使用ModelArts,零基礎小白也能玩轉AI!