当前位置:网站首页>mock-用mockjs模拟后台返回数据
mock-用mockjs模拟后台返回数据
2022-07-02 05:51:00 【想吃凤梨酥】
安装mockjs
npm install mockjs --save-dev
npm install @types/mockjs --save-dev
使用
创建基本引用文件
创建/mock/index.ts
import Mock from "mockjs"
import homeApi from './home'
import userApi from './user'
// 设置200-2000毫秒延时请求数据
// Mock.setup({
// timeout: '200-2000'
// })
// 首页相关
// 拦截的是 /home/getData
Mock.mock(/\/home\/getData/, 'get', homeApi.getStatisticalData)
// 用户相关
Mock.mock(/\/user\/getUser/, 'get', userApi.getUserList)
Mock.mock(/\/user\/del/, 'get', userApi.deleteUser)
Mock.mock(/\/user\/batchremove/, 'get', userApi.batchremove)
Mock.mock(/\/user\/add/, 'post', userApi.createUser)
Mock.mock(/\/user\/edit/, 'post', userApi.updateUser)
Mock.mock(/\/home\/getData/, 'get', homeApi.getStatisticalData)
创建/mock/home.ts
import Mock from 'mockjs'
// 图表数据
let List: any = [];
export default {
getStatisticalData: () => {
for (let i = 0; i < 7; i++) {
List.push(
Mock.mock({
vue: Mock.Random.float(100, 8000, 0, 2),
wechat: Mock.Random.float(100, 8000, 0, 2),
ES6: Mock.Random.float(100, 8000, 0, 2),
Redis: Mock.Random.float(100, 8000, 0, 2),
React: Mock.Random.float(100, 8000, 0, 2),
springboot: Mock.Random.float(100, 8000, 0, 2)
})
)
}
return {
code: 20000,
data: {
// 饼图
videoData: [
{
name: 'springboot',
value: Mock.Random.float(1000, 10000, 0, 2)
},
{
name: 'vue',
value: Mock.Random.float(1000, 10000, 0, 2)
},
{
name: '小程序',
value: Mock.Random.float(1000, 10000, 0, 2)
},
{
name: 'ES6',
value: Mock.Random.float(1000, 10000, 0, 2)
},
{
name: 'Redis',
value: Mock.Random.float(1000, 10000, 0, 2)
},
{
name: 'React',
value: Mock.Random.float(1000, 10000, 0, 2)
}
],
// 柱状图
userData: [
{
date: '周一',
new: Mock.Random.integer(1, 100),
active: Mock.Random.integer(100, 1000)
},
{
date: '周二',
new: Mock.Random.integer(1, 100),
active: Mock.Random.integer(100, 1000)
},
{
date: '周三',
new: Mock.Random.integer(1, 100),
active: Mock.Random.integer(100, 1000)
},
{
date: '周四',
new: Mock.Random.integer(1, 100),
active: Mock.Random.integer(100, 1000)
},
{
date: '周五',
new: Mock.Random.integer(1, 100),
active: Mock.Random.integer(100, 1000)
},
{
date: '周六',
new: Mock.Random.integer(1, 100),
active: Mock.Random.integer(100, 1000)
},
{
date: '周日',
new: Mock.Random.integer(1, 100),
active: Mock.Random.integer(100, 1000)
}
],
// 折线图
orderData: {
date: ['20191001', '20191002', '20191003', '20191004', '20191005', '20191006', '20191007'],
data: List
},
tableData: [
{
name: 'ES6',
todayBuy: Mock.Random.float(100, 1000, 0, 2),
monthBuy: Mock.Random.float(3000, 5000, 0, 2),
totalBuy: Mock.Random.float(40000, 1000000, 0, 2)
},
{
name: '小程序',
todayBuy: Mock.Random.float(100, 1000, 0, 2),
monthBuy: Mock.Random.float(3000, 5000, 0, 2),
totalBuy: Mock.Random.float(40000, 1000000, 0, 2)
},
{
name: 'Vue',
todayBuy: Mock.Random.float(100, 1000, 0, 2),
monthBuy: Mock.Random.float(3000, 5000, 0, 2),
totalBuy: Mock.Random.float(40000, 1000000, 0, 2)
},
{
name: 'springboot',
todayBuy: Mock.Random.float(100, 1000, 0, 2),
monthBuy: Mock.Random.float(3000, 5000, 0, 2),
totalBuy: Mock.Random.float(40000, 1000000, 0, 2)
},
{
name: 'React',
todayBuy: Mock.Random.float(100, 1000, 0, 2),
monthBuy: Mock.Random.float(3000, 5000, 0, 2),
totalBuy: Mock.Random.float(40000, 1000000, 0, 2)
},
{
name: 'Redis',
todayBuy: Mock.Random.float(100, 1000, 0, 2),
monthBuy: Mock.Random.float(3000, 5000, 0, 2),
totalBuy: Mock.Random.float(40000, 1000000, 0, 2)
}
]
}
}
}
}
创建/mock/user.ts
import Mock from 'mockjs'
// get请求从config.url获取参数,post从config.body中获取参数
function param2Obj(url) {
const search = url.split('?')[1]
if (!search) {
return {
}
}
return JSON.parse(
'{"' +
decodeURIComponent(search)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"') +
'"}'
)
}
let List = []
const count = 200
for (let i = 0; i < count; i++) {
List.push(
Mock.mock({
id: Mock.Random.guid(),
name: Mock.Random.cname(),
addr: Mock.mock('@county(true)'),
'age|18-60': 1,
birth: Mock.Random.date(),
sex: Mock.Random.integer(0, 1)
})
)
}
export default {
/** * 获取列表 * 要带参数 name, page, limt; name可以不填, page,limit有默认值。 * @param name, page, limit * @return {
{code: number, count: number, data: *[]}} */
getUserList: config => {
const {
name, page = 1, limit = 20 } = param2Obj(config.url)
console.log('name:' + name, 'page:' + page, '分页大小limit:' + limit)
const mockList = List.filter(user => {
if (name && user.name.indexOf(name) === -1 && user.addr.indexOf(name) === -1) return false
return true
})
const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
return {
code: 20000,
count: mockList.length,
list: pageList
}
},
/** * 增加用户 * @param name, addr, age, birth, sex * @return {
{code: number, data: {message: string}}} */
createUser: config => {
const {
name, addr, age, birth, sex } = JSON.parse(config.body)
console.log(JSON.parse(config.body))
List.unshift({
id: Mock.Random.guid(),
name: name,
addr: addr,
age: age,
birth: birth,
sex: sex
})
return {
code: 20000,
data: {
message: '添加成功'
}
}
},
/** * 删除用户 * @param id * @return {*} */
deleteUser: config => {
const {
id } = param2Obj(config.url)
if (!id) {
return {
code: -999,
message: '参数不正确'
}
} else {
List = List.filter(u => u.id !== id)
return {
code: 20000,
message: '删除成功'
}
}
},
/** * 批量删除 * @param config * @return {
{code: number, data: {message: string}}} */
batchremove: config => {
let {
ids } = param2Obj(config.url)
ids = ids.split(',')
List = List.filter(u => !ids.includes(u.id))
return {
code: 20000,
data: {
message: '批量删除成功'
}
}
},
/** * 修改用户 * @param id, name, addr, age, birth, sex * @return {
{code: number, data: {message: string}}} */
updateUser: config => {
const {
id, name, addr, age, birth, sex } = JSON.parse(config.body)
const sex_num = parseInt(sex)
List.some(u => {
if (u.id === id) {
u.name = name
u.addr = addr
u.age = age
u.birth = birth
u.sex = sex_num
return true
}
})
return {
code: 20000,
data: {
message: '编辑成功'
}
}
}
}
在main.ts
引入基础文件
main.ts
import {
createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './mock'
createApp(App).use(store).use(router).mount('#app')
调用
request("/home/getData", {
method: "get",
}).then((data) => {
console.log(data);
});
边栏推荐
- Alibaba: open source and self-developed liquid cooling data center technology
- 我所理解的DRM显示框架
- XSS basic content learning (continuous update)
- Conglin environmental protection rushes to the scientific and Technological Innovation Board: it plans to raise 2billion yuan, with an annual profit of more than 200million yuan
- Typora installation (no need to enter serial number)
- The Hong Kong Stock Exchange learned from US stocks and pushed spac: the follow-up of many PE companies could not hide the embarrassment of the world's worst stock market
- 460. LFU 缓存 双向链表
- I want to understand the swift code before I learn it. I understand it
- H5 jump applet
- Here comes a new chapter in the series of data conversion when exporting with easyexcel!
猜你喜欢
mysql事务和隔离级别
How to write good code - Defensive Programming Guide
Go language web development is very simple: use templates to separate views from logic
"Original, excellent and vulgar" in operation and maintenance work
Conglin environmental protection rushes to the scientific and Technological Innovation Board: it plans to raise 2billion yuan, with an annual profit of more than 200million yuan
Innovation never stops -- the innovation process of nvisual network visualization platform for Excel import
[PHP是否安装了 SOAP 扩]对于php实现soap代理的一个常见问题:Class ‘SoapClient‘ not found in PHP的处理方法
Importation de studio visuel
《CGNF: CONDITIONAL GRAPH NEURAL FIELDS》阅读笔记
软件测试基础篇
随机推荐
Determine whether there is an element in the string type
Importation de studio visuel
Generate QR code
小程序跳装到公众号
OLED12864 液晶屏
中小型项目手撸过滤器实现认证与授权
PHP gets CPU usage, hard disk usage, and memory usage
all3dp. All Arduino projects in com website (2022.7.1)
The Hong Kong Stock Exchange learned from US stocks and pushed spac: the follow-up of many PE companies could not hide the embarrassment of the world's worst stock market
Centos8 installation mysql8.0.22 tutorial
Win10 copy files, save files... All need administrator permission, solution
Zzuli:1064 encrypted characters
Lingyunguang rushes to the scientific innovation board: the annual accounts receivable reaches 800million. Dachen and Xiaomi are shareholders
【技术随记-08】
15 C language advanced dynamic memory management
KMP idea and template code
js判断移动端还是pc端
3D 打印机 G 代码命令:完整列表和教程
ThreadLocal memory leak
Thread pool overview