vue3 + typescript 全局挂载 axios

vue2 全局挂载 axios

import Vue from 'vue'
import http from './api'
Vue.prototype.$http = http;

注:api 是封装了 axios 的文件夹,这里不详细列出

vue2 使用全局挂载 axios

this.$http.get()

vue3 全局挂载 axios

import { createApp } from 'vue'
import http from './api'
const app = createApp(App);
app.config.globalProperties.$http = http

可以看出,vue3 全局挂载是挂载在 globalProperties,vue2 则是挂载在 prototype

vue3 (非 typescript) 使用全局挂载 axios
这里使用 setup 语法糖

import { getCurrentInstance } from 'vue';
<script setup >
const { proxy } = getCurrentInstance();
proxy.$http.get()
</script>

这里要注意使用的是 getCurrentInstance 的 proxy,不是 ctx,ctx 在生产环境获取不到全局挂载

使用上面的方法,在 typescript 下是会报错的
所以 vue3 (typescript) 使用全局挂载 axios
建 hook 文件夹,里面建 useCurrentInstance.ts
在这里插入图片描述
useCurrentInstance.ts 添加代码:

import { getCurrentInstance,
ComponentInternalInstance } from 'vue'

export default function useCurrentInstance() {
    const { appContext } = getCurrentInstance() as ComponentInternalInstance
    const proxy = appContext.config.globalProperties
    return {
        proxy
    }
}

在组件页面导入 useCurrentInstance.ts

<script setup lang="ts">
import useCurrentInstance from '@/hook/useCurrentInstance'

const {proxy} = useCurrentInstance()
console.log(proxy.$http)
//proxy.$http.get()

</script>

运行后,可以看到 axios 实例已经能够获取

在这里插入图片描述
搞定。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值