Vue3+Ts在Setup语法糖中globalProperties使用定义的函数在组件中获取到的元素始终为any的问题
问题描述
编辑器:VsCode
当我在vue3中封装了一个axios,并想在setup语法糖中使用ta时
封装好axios
// utils/http.ts
import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
export default class HTTP:AxiosInstance{
......
}
在main.ts中挂载到app.config.globalProperties上
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import HTTP from './utils/HTTP'
const app = createApp(App)
const api =new HTTP();
app.config.globalProperties.api=api;
app.mount('#app')
在setup语法糖的组件中调用
//demo.vue
<script setup lang='ts'>
import { reactive } from "@vue/reactivity";
import { getCurrentInstance } from "@vue/runtime-core";
const {
appContext: {
config: {
globalProperties: { api},
},
},
} = getCurrentInstance()!
api.get('/getxxxx')
</script>
在浏览器中代码是正常运行的,封装的axios代码也是未失效,但是在VsCode中使用它时,api的属性解析为any:
同时我在http.ts
中定义的相关方法,如get
,post
等也均为any,而非我期望的AxiosInstance
或AxiosRequestConfig
相关类型
按照我能够找到的方法修改env.d.ts后依旧是只能在setup中解析出any
// env.d.ts
// Vue的默认配置
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
// 对vue进行类型补充说明
declare module '@vue/runtime-core' {
import { AxiosInstance } from "axios";
interface ComponentCustomProperties {
api:AxiosInstance
}
}
虽然并不影响最终打包后的效果但是在coding过程中看不到注释比较难受…
有大佬遇到过类似的问题吗,求解答
请求的封装也可以先实例后,再export出去,然后局部引入的方式去使用
关于vue3的全局属性和函数的定义,官方也有给出定义的方式,不过似乎没有使用的说明,用getCurrentInstance().appContext.config.globalProperties.的方式可以使用,但没有推断提示,需要用getCurrentInstance()?.proxy.才行
(globalproperties-扩充类型:v3.cn.vuejs.org/guide/typescript-s...)
楼主解决这个问题了吗?我也遇到了,查了很多资料也没解决