vue3+ts中对getCurrentInstance的使用

1.在main.js中挂载一个全局属性。拿axios举例


import App from './App.vue';
import axios from './http'    //封装的axios方法
const app = createApp(App);    //创建应用
app.config.globalProperties.$axios = axios;//全局挂载
app.mount('#app')

2.在组件中使用axios

2.1方法一,使用 proxy

import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance() ;
proxy.$axios.post(url).then(res=>{})

2.2 方法二

import { getCurrentInstance } from 'vue'
const currentInstance = getCurrentInstance()
const { $axios} = currentInstance.appContext.config.globalProperties
$axios(url).post(res => {})

以上方法,就是在vue中注册使用全局属性的方法。

注意:

我们在获取Vue3中全局挂载的方法时会这么写:

const { ctx } = getCurrentInstance()

这里的ctx不是setup提供的ctx,打包后在生产环境下是获取不到的。不可使用。

3.在ts中使用axios

以上方法在ts中,会报 类型“ComponentInternalInstance | null”上不存在属性“proxy”的错误

 以下分别对应两种方法,给出对应的解决方法

3.1方法一,proxy写法的解决方法

import { getCurrentInstance} from "vue";
import type { ComponentInternalInstance } from "vue";
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
//此时直接使用proxy.$axios会提示proxy可能为null,因此需要添加?来过滤null
proxy?.$axios.post(url).then(res=> {})

添加完?后又报以下错误

 解决方法为:src文件夹下创建一个如extendProperties.d.ts的文件,内容如下:

import { ComponentCustomProperties } from "@vue/runtime-core";

declare module "@vue/runtime-core" {
  interface ComponentCustomProperties {
    $axios: proxy; // 这里填类型
  }
}
// 必须导出,才能在其他文件中使用
export default ComponentCustomProperties;

 至此,第一种方法解决完毕。

3.2.第二种解决方法

创建一个useCurrentInstance.ts的hook

import { getCurrentInstance } from "vue";
import type { ComponentInternalInstance } from "vue";

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


/*在组件中使用
import useCurrentInstance from "@/hooks/useCurrentInstance";
const { globalProperties } = useCurrentInstance();
globalProperties.$axios(url).then(res=>{})
*/

  • 8
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值