vue vite mock
时间: 2023-12-23 11:27:11 浏览: 34
Vue Vite Mock是一个用于在Vue Vite项目中进行模拟数据的工具。下面是使用Vue Vite Mock的步骤:
1. 首先,安装`mockjs`和`vite-plugin-mock`依赖:
```shell
npm i mockjs vite-plugin-mock -D
```
2. 在`vite.config.ts`文件中进行配置,引入`viteMockServe`并设置`mockPath`:
```javascript
import { defineConfig } from 'vite'
import viteMockServe from 'vite-plugin-mock'
export default defineConfig({
// other configurations...
plugins: [
// other plugins...
viteMockServe({
mockPath: 'mock', // 设置mock文件夹的路径
}),
],
})
```
3. 在项目根目录下创建一个名为`mock`的文件夹。
4. 在`mock`文件夹中创建一个名为`index.ts`的文件,并编写模拟接口数据的代码。例如:
```typescript
import { MockMethod } from 'vite-plugin-mock'
import test from './data/test'
export default [
{
url: "/api/test",
method: 'get',
response: () => {
return {
code: 200,
result: test
}
},
}
] as MockMethod[]
```
5. 在Vue组件中使用模拟数据。例如,在一个使用`<script setup>`的Vue组件中,可以使用`axios`发送请求并获取模拟数据:
```vue
<script setup lang="ts">
import { ref } from "vue";
const t = ref<T>();
interface T {
no: number;
title: string;
}
axios({
method: 'GET',
url: "/api/test"
})
.then(res => {
t.value = res.data.result;
})
</script>
```
这样,你就可以在Vue Vite项目中使用Vue Vite Mock进行模拟数据了。