VUE3+TS+VITE 项目报错 “类型“ComponentInternalInstance | null”上不存在属性“proxy”

VUE3+TS+VITE 项目报错 “类型“ComponentInternalInstance | null”上不存在属性“proxy”

最近创建 VUE3+TS+VITE 模板项目时,封装自己的axios,并将其挂载在全局,这边记录下遇到的一些问题,并分享下是如何解决的。

首先,在main.ts中挂载全局属性。

import http from '@/utils/httpAxios' // 这是你封装的axios方法

const app = createApp(App)
app.config.globalProperties.$http = http
app.mount('#app')

在vue组件中使用

<script setup lang="ts">
import {
    
     getCurrentInstance } from 'vue'

// 使用方式一
const {
    
     proxy } = getCurrentInstance()
proxy .$http.post(import.meta.env.VITE_BASE_URL+'/login').then((data)=>{
    
    
  // do something
})

// 或者方式二,这里我们使用方式一
const currentInstance = getCurrentInstance()
const {
    
     $http } = currentInstance.appContext.config.globalProperties
$http.post(import.meta.env.VITE_BASE_URL+'/login').then((data)=>{
    
    
  // do something
})

</script>

然后就报错:“类型“ComponentInternalInstance | null”上不存在属性“proxy”。查阅相关资料,解决方法如下:

<script setup lang="ts">
import {
    
     getCurrentInstance, ComponentInternalInstance } from 'vue'
const {
    
     proxy } = getCurrentInstance() as ComponentInternalInstance
// 然后使用 proxy.$http
</script>

随后又报这样的错误:类型“ComponentPublicInstance<{}, {} ... , ComponentOptionsBase<any, any, ...>, {}, {}>”上不存在属性“$http”

错误:类型“ComponentPublicInstance<{}, {}, {}, {}, {}, {}, {}, {}, false, ComponentOptionsBase<any, any, any, any, any, any, any, any, any, {}, {}, string, {}>, {}, {}>”上不存在属性“$http”。

查了许多的解决方案,最后看到一种方案,在src文件夹下创建一个如extendProperties.d.ts的文件,内容如下:

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

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

至此,报错都解决了,如需添加其他全局变量,则往下加属性名和对应类型。

猜你喜欢

转载自blog.csdn.net/weixin_42927679/article/details/131603089
今日推荐