Paolo Donato Navarro
Paolo Donato Navarro

Reputation: 149

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

I want to have a global var for the url of my server.

I write this on my main.ts

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

and then trying to use it inside App.vue

console.log(this.$apiUrl)

I can see the url in the browser's console.

But I'm getting this error: Property '$apiUrl' does not exist on type 'App'.Vetur(2339)

and I cant continue, cause in some parts of the app this.$apiUrl is undefined for some reason.

How can I fix it?

Upvotes: 1

Views: 1305

Answers (2)

tao
tao

Reputation: 90013

Note the Class API proposal has been abandoned. To use Vue + Typescript until Vue 3 is out, you're better off using Vue.extend({}) component style:

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

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

For adding global typings to your Vue instance, read Typescript Support.

Specifically, you should add this to your shims:

import Vue from 'vue'

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

Upvotes: 1

Paolo Donato Navarro
Paolo Donato Navarro

Reputation: 149

Solved! I need to add the $apiUrl to the types of Vue

I create a .d.ts file inside my @types folder and add the following

import Vue from 'vue'

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

Upvotes: 0

Related Questions