簡體   English   中英

具有 vue-class-components 和 typescript 的 vuejs 實例屬性時出錯

[英]Error having vuejs instance properties with vue-class-components and typescript

我想為我的服務器的 url 有一個全局變量。

我在我的 main.ts 上寫了這個

Vue.prototype.$apiUrl = "http://localhost:3000";

然后嘗試在 App.vue 中使用它

console.log(this.$apiUrl)

我可以在瀏覽器的控制台中看到 url。

但我收到此錯誤: Property '$apiUrl' does not exist on type 'App'.Vetur(2339)

我無法繼續,因為在應用程序的某些部分 this.$apiUrl 由於某種原因未定義。

我該如何解決?

請注意Class API 提案已被放棄。 要在 Vue 3 發布之前使用 Vue + Typescript,最好使用Vue.extend({})組件樣式:

<script lang="ts">
  import Vue from 'vue';

  export default Vue.extend({
    ...
  })
</script>

要向 Vue 實例添加全局類型,請閱讀Typescript 支持

具體來說,您應該將其添加到您的墊片中:

import Vue from 'vue'

declare module 'vue/types/vue' {
  interface Vue {
    $apiUrl: string;
  }
}

解決了! 我需要將 $apiUrl 添加到 Vue 的類型中

我在 @types 文件夾中創建了 adts 文件並添加了以下內容

import Vue from 'vue'

declare module 'vue/types/vue' {
  interface Vue {
    $apiUrl: string
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM