vue3 学习笔记05 -- mock的使用
mock主要用途仅为模拟后端数据接口
-
安装依赖
npm i mockjs vite-plugin-mock@2.9.8 -D
-
根目录下创建mock文件夹
-
/mock/login/index.mock.ts -- 模拟登录接口
tsexport default [ // 用户登录接口 { url: '/mock/user/login',//请求地址 method: 'post',//请求方式 response: ({ body }:any) => { return { "code": 200, "message": "成功", "data": { "token": "1234567890xxx", "expireAt": 1720505458920, "refreshToken": "12345678765xxx", "userInfo": { "id": 20, "name": '小明', "phone": 15984958697 } } } }, } ]
-
src/index.ts
tsimport { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer' import login from './login/index.mock'; const modules = { login // 其他模块... }; const mockModules: any[] = [] Object.keys(modules).forEach(async (key) => { if (key.includes('_')) { return } mockModules.push(...(modules[key] as any)) }) export function setupProdMockServer() { createProdMockServer(mockModules) }
-
-
vite.config.ts配置
ts
import { defineConfig, loadEnv, UserConfig, ConfigEnv } from 'vite'
// mock插件提供的方法
import { viteMockServe } from 'vite-plugin-mock'
export default defineConfig({
plugins: [
vue(),
viteMockServe({
mockPath: './mock/',
localEnabled: true,
injectCode: `
import { setupProdMockServer } from '../mock/index'
setupProdMockServer()
`
}),
],
server:{
host: '0.0.0.0', // 允许IP访问
proxy: {
'/api': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
}
}
}
})
- 具体调用接口使用请看
axios请求