前端开发过程中时常遇到,页面已经写好了,但是后端还没接口的情况。 后端写好了接口项目又着急着测试上线,这时项目进程压力将会给到前端,加班将是必然。 该方案可以很好的处理这个问题。
前提:
- 后端规定好接口返回格式如:
ts
interface ApiResponse<T = any> {
code: number
message: string
data: T
success: boolean
timestamp?: number
}
- 拿到后端数据库字段命名规范,统一规范命名变量
- 列表的命名:list,data,...
- 数量的统计:count,total,all,...
- 页数:page,pageNum,...
- 条数:size,PageSize,limit,...
- ...
- 明确增删改查的请求方式,GET POST PUT DEL
相关依赖
插件:vite-plugin-mock-dev-server.netlify.app/zh/
安装依赖 pnpm add -D vite-plugin-mock-dev-server
具体操作
配置vite.config.ts
ts
import { defineConfig } from 'vite'
import { mockDevServerPlugin } from 'vite-plugin-mock-dev-server'
export default defineConfig({
plugins: [
...
mockDevServerPlugin(),
],
define: {},
server: {
cors: false,
// 在 proxy 中配置的 代理前缀, mock-dev-server 才会拦截并mock
proxy: {
'^/api': {
target: '',
},
},
},
})
在根目录下创建文件
目录接口
mock/
├── user/
│ ├── login.ts
│ ├── register.ts
编辑login.ts文件(只有两个账号:admin/Admin123 或 demo/Demo123 通过登录)
ts
import { defineMock } from 'vite-plugin-mock-dev-server'
const data = {
code: 0,
message: '登录成功',
success: true,
timestamp: Date.now(),
data: {
token: 'test',
expire: Date.now() + 1000 * 60 * 60 * 24,
userinfo: {
name: 'test',
avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
},
permission: [
{
pathId: "/",
name: "首页",
add: true,
edit: true,
del: true,
list: true,
auth: true,
},
{
pathId: "/system/user",
name: "用户管理",
add: true,
edit: true,
del: true,
list: true,
auth: true,
},
],
}
}
export default defineMock({
url: '/api/login',
method: 'POST',
body({ body }) {
const { username, password} = body
if (username === 'admin' && password === 'Admin123') {
return data
}
if (username === 'demo' || password === 'Demo123') {
return data
}
return {
code: 1,
message: '登录失败',
success: false,
timestamp: Date.now(),
}
}
})
请求案例:
js
fetch('/api/login', {
method: 'POST',
body: JSON.stringify({
username: 'admin',
password: 'Admin123',
}),
}).then((res:any) => {
if (response.code !== 0) {
ElMessage.error(res.message)
return
}
ElNotification({
title: '登录成功',
message: `欢迎回来,${response.data.userinfo.username}!`,
type: 'success',
duration: 3000
})
router.push('/')
})