vue3 之mock数据的使用 (js版本)
- 安装:
npm i mockjs vite-plugin-mock -D
vite.config.js配置
import vue from '@vitejs/plugin-vue'
import {
viteMockServe
} from 'vite-plugin-mock'
import path, {
resolve
} from 'path'
export default ({
command,
mode
}) => {
return {
base: "./",
server: {
host: '0.0.0.0',
port: 5006,
open: false,
},
resolve: {
alias: {
'@': resolve(__dirname, 'src'),
}
},
plugins: [
vue({}),
viteMockServe({
mockPath: 'mock',
localEnabled: command === 'serve',
logger: true
}),
]
}
}
根目录下创建 mock / app.js
export default [{
url: '/mock/api/getAppInfo',
method: 'get',
response: () => {
return {
code: 0,
title: 'mock请求测试'
}
}
}]
使用 axios 请求mock数据
<template>
<div />
</template>
<script setup>
import axios from 'axios'
axios.get('/mock/api/getAppInfo').then((res) => {
console.log(res)
})
</script>
vue3 之mock数据的使用 (ts版本)
vite.config.ts 配置
import { UserConfigExport, ConfigEnv } from 'vite'
import { viteMockServe } from 'vite-plugin-mock'
import vue from '@vitejs/plugin-vue'
export default ({ command }: ConfigEnv): UserConfigExport => {
return {
plugins: [
vue(),
viteMockServe({
mockPath: 'mock',
localEnabled: command === 'serve',
}),
],
}
}