typescriptvue.jsvetur

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?


Solution

  • 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;
      }
    }