True fragrance law! Mock (Basic)

This article mainly introduces the configuration, installation, and use of mocks. Mocks are mainly divided into dev mocks and prod mocks

configuration

Official documentation: viet-plugin-mock

Installation-dependent dependencies

yarn add vite-plugin-mock mockjs
Copy the code

Creating a Mock folder

vite.config.js

import setting from './src/settings'
const prodMock = setting.openProdMock
viteMockServe({
  // Whether to enable ts support
  supportTs: true.// Set mockPath to the mock directory under the root
  mockPath: 'mock',
  // Sets whether to monitor changes in files in the folder corresponding to mockPath
  localEnabled: command === 'serve',
  // Whether mock can be used in prod
  prodEnabled: prodMock,
  // Inject the relevant mock request API when prod
  injectCode: `
import { setupProdMockServer } from './mockProdServer';
setupProdMockServer();
`,
  // Whether to display request logs on the console
  logger: true})].Copy the code

The dev environment for the mock above is configured. If you want to use mock in production environment, you need to continue to configure

mockProdServer.js

import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer'
// import.meta.glob dynamically imports the.js file in the mock folder. The import principle is similar to store
const modulesFiles = import.meta.globEager('.. /mock/*.js')
let modules = []
for (const path in modulesFiles) {
  modules = modules.concat(modulesFiles[path].default)
}
export function setupProdMockServer() {
  createProdMockServer([...modules])
}
Copy the code

use

Mock file names are recommended to be the same as directory folders in views.

Create.js files, such as example.js, in the mock folder

mock/example.js

export default[{url: '/getMapInfo'.method: 'get'.response: () = > {
      return {
        code: 0.title: 'Mock request test'}}}]Copy the code

The request is then invoked directly, as in mockTest.vue

views/example/MockTest.vue

<template> <div class="mockTest"> <div> < el-button@click ="listReq" Type ="primary"> Click send mock request </el-button> </div> </template> <script setup> // mock Address https://blog.csdn.net/weixin_42067720/article/details/115579817 // import '@/mock/index.js' import mockAxiosReq from '@/utils/mockAxiosReq' const listReq = () => { mockAxiosReq.get('/getMapInfo').then((res) => { if (res.data) { console.log(res.data) alert(res.data.title) } }) } </script>Copy the code

Look at the feeling is very simple, very fragrant!!