Appearance
使用Mock.js模拟数据
正在使用一个 Vant + Vite 移动端框架,里面有 Mock 功能。
在框架中一封装好功能,只需要在根目录的 ./mock
文件下创建 api 文档。
在框架中使用
js
// http://mockjs.com/examples.html#Object
const loginInfo = () => {
const result = {
token: 'token'
}
return result
}
const userInfo = () => {
const result = {
id: 9527,
avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
name: '灰是小灰灰的灰',
phone: '15988888888',
email: 'abc@qq.com',
identity: '',
roles: ['superadmin'],
}
return result
}
export default [
{
url: '/api/getUserInfo',
type: 'get',
response: () => {
return {
code: 200,
message: 'success',
data: userInfo()
}
}
},
]
配置:
js
// /src/mockProdServer.js
import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer'
import userMock from '../mock/user'
import demoMock from '../mock/demo'
import articleMock from '../mock/article'
import qualityLotMock from '../mock/qualityLot'
import repairLotMock from '../mock/repair'
import maintenanceLotMock from '../mock/maintenance'
export const mockModules = [...userMock, ...demoMock, ...articleMock, ...qualityLotMock, ...repairLotMock ,...maintenanceLotMock]
export function setupProdMockServer(){
createProdMockServer(mockModules)
}
js
import vue from '@vitejs/plugin-vue'
import DefineOptions from 'unplugin-vue-define-options/vite'
import legacy from '@vitejs/plugin-legacy'
import { visualizer } from 'rollup-plugin-visualizer'
import { viteMockServe } from 'vite-plugin-mock' // https://github.com/anncwb/vite-plugin-mock/blob/HEAD/README.zh_CN.md
import { svgBuilder } from '../config/svgBuilder.js'
import vueJsx from '@vitejs/plugin-vue-jsx'
export function composePlugins(command, VITE_LEGACY) {
const prodMock = true
const lifecycle = process.env.npm_lifecycle_event
return [
vue(),
DefineOptions(),
vueJsx(),
svgBuilder('./src/icons/svg/'),
VITE_LEGACY
? legacy({
targets: [
'> 1%, last 1 version, ie >= 11',
'safari >= 10',
'Android > 39',
'Chrome >= 60',
'Safari >= 10.1',
'iOS >= 10.3',
'Firefox >= 54',
'Edge >= 15',
],
additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
polyfills: ['es.promise.finally', 'es/map', 'es/set'],
modernPolyfills: ['es.promise.finally'],
})
: null,
lifecycle === 'report'
? visualizer({
open: true,
gzipSize: true,
brotliSize: true,
filename: 'report.html',
})
: null,
viteMockServe({
mockPath: 'mockw',
watchFiles: true,
supportTs: false,
localEnabled: command === 'serve',
prodEnabled: command !== 'serve' && prodMock,
injectCode: `
import { setupProdMockServer } from './mockProdServer';
setupProdMockServer();
`,
logger: false,
}),
]
}
当访问接口 /api/getUserInfo
时,请求的是mock起的服务,结果返回:
js
return {
code: 200,
message: 'success',
data: userInfo()
}
正则匹配
实际请求中,会有query参数,分页信息等拼接在接口地址后面。如果需要忽略这些参数,可以用正则去匹配:
js
{
url: RegExp('/api/eam/EamRepair/view/' + '.*'),
method: 'get',
response: () => {
return {
code: 200,
message: 'test',
data: detail(),
}
},
},