VUE3+TS+VITE-Projektfehler „Die Eigenschaft „proxy“ existiert nicht für den Typ „ComponentInternalInstance | null“

VUE3+TS+VITE-Projektfehler „Die Eigenschaft „proxy“ existiert nicht für den Typ „ComponentInternalInstance | null“

Als ich VUE3+TS+VITEkürzlich ein Vorlagenprojekt erstellt habe, habe ich meine Axios gepackt und global gemountet. Hier werde ich einige aufgetretene Probleme aufzeichnen und mitteilen, wie ich sie lösen kann.

Mounten Sie zunächst main.tsdie globalen Eigenschaften in .

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

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

Wird in Vue-Komponenten verwendet

<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>

Dann wird ein Fehler gemeldet: “类型“ComponentInternalInstance | null”上不存在属性“proxy”. Überprüfen Sie die relevanten Informationen. Die Lösung lautet wie folgt:

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

Dann wurde dieser Fehler gemeldet: 类型“ComponentPublicInstance<{}, {} ... , ComponentOptionsBase<any, any, ...>, {}, {}>”上不存在属性“$http”.

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

Nachdem ich viele Lösungen überprüft hatte, sah ich endlich eine Lösung, indem ich srceine Datei wie im Ordner erstellte extendProperties.d.ts. Der Inhalt lautet wie folgt:

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

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

Bisher wurden alle Fehler behoben. Wenn Sie weitere globale Variablen hinzufügen müssen, fügen Sie den Attributnamen und den entsprechenden Typ hinzu.

おすすめ

転載: blog.csdn.net/weixin_42927679/article/details/131603089