一、安裝mock、axios

npm i vite-plugin-mock -D
npm i axios  -S

二、src目录下创建mock文件夹

1.创建index.ts

import Mock from "mockjs";
import { MockParams } from "./typing";
import apis1 from "./apis1";
const mocks = [...apis1];
//设置延时时间
Mock.setup({
  timeout: "300",
});

export function mockXHR() {
  let i: MockParams;
  for (i of mocks) {
    Mock.mock(new RegExp(i.url), i.type || "get", i.response);
  }
}

2.创建user.ts,编写请求请求接口参数 以及 返回值

import Mock from "mockjs";
export default [
  {
    url: "/api/user",
    type: "get",
    response: () => {
      return {
        code: 200,
        message: "成功",
        data: {
          name: "testName",
        },
      };
    },
  },
  {
    url: "/auth/oauth/token",
    type: "post",
    response: (option: any) => {
      const $name = JSON.parse(option.body).name;
      if ($name) {
        return Mock.mock({
          code: 200,
          message: "成功",
          data: {
            name: "testToken",
          },
        });
      } else {
        return Mock.mock({
          code: 400,
          message: "未提交参数",
        });
      }
    },
  },
];

3.创建typing.ts

export interface MockParams {
  url: string;
  type: string;
  data?: any;
  params?: any;
  response(option?: any): Record<string, unknown>;
}

4.创建mock-vue.d.ts

declare module "mockjs";


二、引入mian.js

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from "./router";
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

import axios from "axios";

import { mockXHR } from "./mock/index";

mockXHR()

const app = createApp(App)
app.provide("$axios", axios)
app.use(router)
app.use(ElementPlus)
app.mount('#app')

三、使用mock

<script  setup lang="ts">
  import  { Nav }  from "../../components";
  import axios from "axios";
    axios.get('/api/user').then(res=>{
      console.log('res',res);
    })
</script>

GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐