1.下载mock接口
bash
pnpm i vite-plugin-mock
2.配置vite.config.ts
TypeScript
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path";
//引入svg需要用到的插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
//mock插件提供方法
import { viteMockServe } from 'vite-plugin-mock'
export default defineConfig(({ command }) => {
return {
plugins: [vue(),
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
symbolId: 'icon-[dir]-[name]'
}),
viteMockServe({
localEnabled: command === 'serve',
})
],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
}
},
css: { //scss全局变量的配置
preprocessorOptions: {
scss: {
javascriptEnabled: true,
additionalData: `@import "./src/styles/variable.scss";`
}
}
},
}
})
如果localEnabled爆红的话就把vite-plugin-mock的版本换成2.9.6
bash
"vite-plugin-mock": "^2.9.6",
3.项目文件夹下创建mock文件夹
文件名看情况
TypeScript
function createUserList() {
return [
{
id: 1,
name: '张三',
age: 18,
password: '123456'
},
{
id: 2,
name: '李四',
age: 20,
password: '123456'
}
]
}
//对外暴露一个数组:数组里面包含两个接口
//登录假的接口
//获取用户信息的假的接口
export default [
{
url: '/api/user/login',
method: 'post',
response: ({ body }) => {
const { username, password } = body
const userList = createUserList()
const user = userList.find(item => item.name === username && item.password === password)
if (user) {
return {
code: 200,
message: '登录成功',
data: user
}
} else {
return {
code: 400,
message: '用户名或密码错误',
data: null
}
}
}
}
]