The last chapter mainly completed the breadcrumb and tagsView components Vite2 + VUe3 + TS + ElementPlus to build the background management system from zero (5)
This chapter begins by adding mockJS mock data
1. Install MockJS and viet-plugin-Mock
The node version: > = 12.0.0
Vite version: > = 2.0.0
- yarn add mockjs -S
- yarn add vite-plugin-mock -D
Or:
- npm install mockjs -S
- npm install vite-plugin-mock -D
ViteMockServe configuration:
{ mockPath? :string; // Set the mock data.ts file storage foldersupportTs? :boolean; // Can read ts file module.ignore? :RegExp | ((fileName: string) = > boolean);// Ignores the file in the specified formatignoreFiles? :string[]; // Ignore the specified folderwatchFiles? :boolean; // Whether to monitor changes in files in the folder corresponding to mockPathlocalEnabled? :boolean;// Whether to enable the local xxx.ts file. False disables the mock functionprodEnabled? :boolean; // Package whether to enable mockconfigPath? :string; // Simulate the data entry readinjectFile? :string; // injectCode injectCode file, default project root directory SRC /main.{ts,js}injectCode? :string; // Whether the code is injected at the bottom of the corresponding injectFilelogger? :boolean; // Whether to display request logs on the console
}
Copy the code
2.Mock file example
Create a new directory under the root directory:
mock/demo/user.ts
mock/_createMockServer.ts
user.ts:
import { MockMethod } from 'vite-plugin-mock'
function createFakeUserList() {
return[{userId: '1'.username: 'admin'.realName: 'admin'.desc: 'manager'.password: '123456'.token: 'fakeToken1'.roles: [{roleName: 'Super Admin'.value: 'super'}]}, {userId: '2'.username: 'test'.password: '123456'.desc: 'tester'.token: 'fakeToken2'.roles: [{roleName: 'Tester'.value: 'test'}]}]}function resultSuccess(
result: Record<string, unknown>,
{ message = 'ok' } = {}
) {
return {
code: 0,
result,
message,
type: 'success'}}function resultError(
message = 'Request failed',
{ code = -1, result = null } = {}
) {
return {
code,
result,
message,
type: 'error'}}export default [
// mock user login
{
url: '/mock-api/login'.timeout: 200.method: 'post'.response: ({ body }) = > {
const { username, password } = body
const checkUser = createFakeUserList().find(
(item) = > item.username === username && password === item.password
)
if(! checkUser) {return resultError(Incorrect Account or password! ')}const {
userId,
username: _username,
token,
realName,
desc,
roles
} = checkUser
return resultSuccess({
roles,
userId,
username: _username,
token,
realName,
desc
})
}
}
] as MockMethod[]
Copy the code
_createMockServer. Ts:
import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer'
const modules = import.meta.globEager('./**/*.ts')
const mockModules: any[] = []
Object.keys(modules).forEach((key) = > {
if (key.includes('/ _')) {
return} mockModules.push(... modules[key].default) })/** * Used in a production environment. Need to manually import all modules */
export function setupProdMockServer() {
createProdMockServer(mockModules)
}
Copy the code
Note: import.meta. GlobEager may have an error
Modify the tsconfig.json configuration include property:
"include": [
"src/**/*.ts"."src/**/*.d.ts"."src/**/*.tsx"."src/**/*.vue"."mock/**/*.ts" / / + + added
]
Copy the code
3.配置使用 vite-plugin-mock
Create a new file under SRC /plugins
configMockPlugin.ts
/** * Mock plugin for development and production. * https://github.com/anncwb/vite-plugin-mock */
import { viteMockServe } from 'vite-plugin-mock';
export function configMockPlugin(isBuild: boolean) {
return viteMockServe({
ignore: / ^ \ _ /,
mockPath: 'mock'.localEnabled: !isBuild,
prodEnabled: isBuild,
injectCode: ` import { setupProdMockServer } from '.. /mock/_createMockServer'; setupProdMockServer(); `}); }Copy the code
4. Perfect vite. Config. Ts
Currently vite. Config. ts is exported directly in this way;
export default defineConfig({
...
})
Copy the code
Is amended as:
export default ({ command, mode }: ConfigEnv): UserConfigExport= > {
const isBuild = command === 'build'
returndefineConfig({ ... })})Copy the code
ConfigEnv and UserConfigExport are imported from ‘vite’
import { defineConfig, ConfigEnv, UserConfigExport } from ‘vite’
Then add a new item to the plugins configuration:
ConfigMockPlugin (isBuild) // Mock requests
5. Test the mock
Add the following to the SRC directory:
api/login/index.ts
Index. Ts:
import request from '@/utils/request';
// User login
export function signIn(params: object) {
return request({
url: '/mock-api/login'.method: 'post'.data: params,
});
}
Copy the code
Modify the SCR/views/demo/index. Vue:
<template> <div> <div>demo</div> <el-button @click="handleSignIn"> </el-button> </div> </template> <script> import {signIn} from '@/api/login/index' export default { setup(){ const handleSignIn = ()=>{ signIn().then((res)=>{ console.log(res); }).catch((err)=>{ console.log(err); }) } return { handleSignIn } } } </script> <style> </style>Copy the code
Modify the SRC/utils/request. Ts:
.export const PATH_URL: string ='/'.Copy the code
Enter /demo and click the login button to obtain the following:
Mock mock data was successfully obtained locally. Procedure