Mock前端简单易用的自行模拟数据提高开发效率
官网
http://mockjs.com/examples.html
根据官网数据模板模拟对应需要的数据
插件
npm i vite-plugin-mock mockjs -D
Or
npm i --save-dev @types/mockjs
Or
pnpm i vite-plugin-mock mockjs -D
Or
pnpm i --save-dev @types/mockjs
vite.config.js文件中
import { viteMockServe } from "vite-plugin-mock"
plugins: [
viteMockServe({
mockPath: './src/mock',
localEnabled: true
}),
],
创建mock文件夹,index.ts文件 推荐使用第二种方式↓
import type { MockMethod } from 'vite-plugin-mock'
import Mock from 'mockjs'
const rules: MockMethod[] = [
{
url: '/home/page/doc',
method: 'get',
response: () => {
const data = []
for (let i = 0; i < 10; i++) {
data.push(
Mock.mock({
"id": "@id",
"name": "@ctitle(3,10)",
"avatar": "Random.dataImage('200x100')",
"hospitalName": "@ctitle(10,40)"
}
))
}
return {
code: 0,
message: "获取数据成功",
data: {
"pageTotal": 0,
"total": 0,
rows: data
},
}
},
},
]
export default rules
Or
import type { MockMethod } from 'vite-plugin-mock'
export default [
{
url: '/login',
method: "post",
timeout: 3000,
response: {
code: 0,
data: {
id: "@id",
name: "@name",
token: "@guid",
msg: '@shuffle(["a", "e", "i", "o", "u"])',
ip: "@ip()",
title: "@cparagraph",
time: '@datetime("yyyy-MM-dd A HH:mm:ss")'
}
}
}
] as MockMethod[]
学习如何生成想要的参数
打开模拟数据官方文档,找到对应@符的参数名进行使用
请求数据时。
import axios from "axios";
const add = async () => {
let res = await axios.post("/login");
console.log(res);
};
add();