Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reach global window variable from index.html in a Vue component

If i have an Stencil.js component that i load in to my Vue project like this:

index.html:

  <script type="module"
    src="https://xxxxxx.s3-eu-west-1.amazonaws.com/topbar.esm.js">
  </script>

  <script>
    window.addEventListener('topbarLoaded', function (data) {
      window.topbar = data.detail;
      console.log('topbar was loaded and here it is:', window.topbar);
    });
  </script>

I then want to reach the topbar information in my vue components. Something like

VueComponent.vue

<script lang="ts">
   import { Component, Prop, Vue } from "vue-property-decorator";

   @Component({
     name: 'testcomp'
   })
   export default class PodList extends Vue {
      data() {
         return {
            topbar: window.topbar // Error: Property 'topbar' does not exist on type 'Window & typeof globalThis'
         }
      }
   }
</script>

So here I want all stuff i have from my topbar to be accessible in my Vue component. As it is now, if I open Chrome devtools i can write topbar.user and get all information of user, but I also want this information to be reachable in all vue components.

like image 623
Johan Byrén Avatar asked Nov 21 '25 15:11

Johan Byrén


1 Answers

The problem is that TypeScript doesn't know that property. You can solve that in several ways:

  1. Add // @ts-ignore on the previous line. This suppresses errors on the next line.
  2. Cast to any: (window as any).topbar
  3. Define the property in the window interface:
declare global {
    interface Window { topbar: any; }
}
like image 104
Thomas Avatar answered Nov 23 '25 06:11

Thomas