vite2:全局自动导入api

目录

实现要点:

一、目录结构组织

二、自动导入实现

1、在business文件夹中建立各个模块对应的封装好的API接口,如上图:user.ts

2、在api/index.ts中读取business文件夹下的所有文件

3、在main.ts中引入api/index.ts中导出的modules,并注册到vue上(在vue3中不能使用prototype注册全局属性等)

4、在.vue文件中使用自动导出的api


实现要点:

1、在vite中读取某个目录下的所有文件:import.meta.globEager 或 import.meta.glob,在webpack搭建的项目中使用的是:require.context

2、vue3中给挂载全局属性:config.globalProperties

3、vue3中使用全局属性:getCurrentInstance

详细使用方式请阅读全文

一、目录结构组织

二、自动导入实现

1、在business文件夹中建立各个模块对应的封装好的API接口,如上图:user.ts

// user.ts
import { post, get } from "@/config/request";
/**
 * @interface loginParams -登录参数
 * @property {string} userName -用户名
 * @property {string} password -用户密码
 */
interface LoginParams {
    userName: string;
    password: string;
}
export function login(data: LoginParams) {
    return post("/api/login", data);
}

2、在api/index.ts中读取business文件夹下的所有文件

// api/index.ts
// vite中读取文件需要使用import.meta.globEager 或 import.meta.glob
const requireComponent = import.meta.globEager("./business/*.ts");
let modules: any = {};

Object.entries(requireComponent).forEach(([k, v]) => {
    Object.assign(modules, v);
});

export default {
    modules,
};

3、在main.ts中引入api/index.ts中导出的modules,并注册到vue上(在vue3中不能使用prototype注册全局属性等)

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import { store, key } from "./store";
import "normalize.css/normalize.css";
import "@/styles/index.less";
import api from "./api/index";

const app = createApp(App);
// vue3挂载全局属性需要使用 config.globalProperties
app.config.globalProperties.$axios = api.modules;
app.use(router).use(store, key).mount("#app");

4、在.vue文件中使用自动导出的api

import { getCurrentInstance } from "vue";
const { proxy }: any = getCurrentInstance();
const login = async ()=>{
    let res = await proxy.$axios.login(ruleForm)
}

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值