Vue3 全局注册 $api 的几种方案
Vue3 全局注册 $api 的几种方案
方案一:全局属性注册(最常用)
注册方式
// main.js
import { createApp } from 'vue'
import * as api from './api/index.js'
const app = createApp(App)
app.config.globalProperties.$api = api
使用方式
// 组件中使用
<script setup>
import { getCurrentInstance } from 'vue'
const { proxy: { $api } } = getCurrentInstance()
const handleSubmit = async () => {
const res = await $api.getUserInfo()
}
</script>
优点: 简单直接,Vue2 升级友好
缺点: TypeScript 支持需要额外配置
方案二:provide/inject 注入
注册方式
// main.js
import { createApp } from 'vue'
import * as api from './api/index.js'
const app = createApp(App)
app.provide('$api', api)
使用方式
// 组件中使用
<script setup>
import { inject } from 'vue'
const $api = inject('$api')
const handleSubmit = async () => {
const res = await $api.getUserInfo()
}
</script>
优点: 更符合 Vue3 设计理念,TypeScript 友好
缺点: 需要在每个组件中注入
方案三:插件方式注册
注册方式
// plugins/api.js
export default {
install(app, options) {
const api = options.api
app.config.globalProperties.$api = api
app.provide('$api', api)
}
}
// main.js
import { createApp } from 'vue'
import apiPlugin from './plugins/api.js'
import * as api from './api/index.js'
const app = createApp(App)
app.use(apiPlugin, { api })
使用方式
// 方式1:全局属性
const { proxy: { $api } } = getCurrentInstance()
// 方式2:注入
const $api = inject('$api')
优点: 提供多种使用方式,扩展性好
缺点: 代码稍复杂
方案四:Composables 封装
注册方式
// composables/useApi.js
import * as api from '@/api/index.js'
export function useApi() {
return api
}
使用方式
// 组件中使用
<script setup>
import { useApi } from '@/composables/useApi'
const $api = useApi()
const handleSubmit = async () => {
const res = await $api.getUserInfo()
}
</script>
优点: 完全符合 Composition API 风格,按需导入
缺点: 需要在每个使用的组件中导入
方案五:全局挂载 + Composables 结合
注册方式
// main.js
import { createApp } from 'vue'
import * as api from './api/index.js'
const app = createApp(App)
app.config.globalProperties.$api = api
// composables/useApi.js
import { getCurrentInstance } from 'vue'
export function useApi() {
const { proxy } = getCurrentInstance()
return proxy?.$api
}
使用方式
// 组件中使用
<script setup>
import { useApi } from '@/composables/useApi'
const $api = useApi()
const handleSubmit = async () => {
const res = await $api.getUserInfo()
}
</script>
优点: 兼顾便利性和规范性
缺点: 需要额外的 composable 层
推荐方案对比
| 方案 | 简单度 | TypeScript 支持 | Vue3 风格 | 推荐指数 |
|---|---|---|---|---|
| 全局属性 | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐ |
| provide/inject | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| 插件方式 | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐ |
| Composables | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| 全局+Composables | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
快速选择建议
- 小型项目 → 方案一:全局属性注册
- 中型项目 → 方案五:全局挂载 + Composables 结合
- 大型项目 → 方案四:Composables 封装
- TypeScript 项目 → 方案二或方案四

浙公网安备 33010602011771号