Access the global window variable from index.html within a Vue component

In my Vue project, I am incorporating an Stencil.js component in the following manner:

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>

Now, I am trying to access the topbar information within my Vue components. For example,

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>

I want to make all the content of my topbar accessible in every Vue component. Currently, I can access topbar.user in Chrome devtools for user information, but I need this data to be available across all Vue components.

Answer №1

The issue arises from TypeScript not recognizing the property. There are a few ways to tackle this problem:

  1. Insert // @ts-ignore on the line above to ignore errors on the subsequent line.
  2. Typecast to any: (window as any).topbar
  3. Define the property within the window interface:
declare global {
    interface Window { topbar: any; }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing a single image within a v-for loop of images in Vue

I am currently working with an array in Vue where I am using v-for to create 3 columns of information. Each column includes an image, and I would like to be able to change only the specific image that is being hovered over without affecting any others. How ...

Refreshing a page in Angular 4/5 using TypeScript

I am currently working on a single-page application that utilizes routes for navigation: this.router.navigate(['/customer-home'], { skipLocationChange: true }); While on the customer home page, I have a feature to add a new customer via a REST ...

Converting a JavaScript function to work in TypeScript: a step-by-step guide

When writing it like this, using the this keyword is not possible. LoadDrawing(drawing_name) { this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB,drawing_name); } LoadCB(drawing, drawing_name) { if (drawing == null) { return; ...

Transforming an object into an interface in TypeScript

Recently, I have started learning Typescript and am currently working on a project where I am building a REST API. In this project, I have defined a specific model for my request payload. However, even after typecasting, the type of 'resObj' rem ...

Utilizing vuelidate in Vue 3: Overcoming Decorators Challenge in Composition API (`<script setup>`)

Currently working on upgrading from vue 2 to vue 3 and encountering an error with the @Component decorator: "Decorators are not valid here.ts(1206) (alias) Component(options: Vue.ComponentOptionsBase<Vue, any, any, any, any, any, any, any, string, ...

Comparing JSON objects with JavaScript models: A guide

Currently I'm working with angular 2 and I have an array of data. data: MyModel[] = [ { id: 1, name: 'Name', secondName: 'SecondName' } In addition, I have created the interface MyModel: interface MyModel { id: number, nam ...

Vue's drag-and-drop functionality is effective for dragging entire groups, but it does not work

Below is the code that enables dragging of groups in toListFetchRouteA1: <draggable id="first" data-source="juju" :list="toListFetchRouteA1" class="list-group" draggable=".item" group="a"> <div class="list-group-item item" v-for="teamfetch in ...

Error encountered when parsing JSON data in Vue.js due to presence of invalid characters in the

I have been working on a web application that allows me to upload a JSON file, make changes to it, and then download it. However, the resulting JSON is not valid because certain characters seem to change during the process. Even when I simply upload and do ...

Issue with VueJS/VueX: Watch method not triggering when state property is an array

I am facing an issue with a simple flow in my application: First, I call a VueX action to store multiple cars on the backend side. Then, I call a mutation to store newly created cars. Finally, I declare a watcher that should be triggered whenever the arr ...

Issue with Vue 2: Promise does not resolve after redirecting to another page

Although I realize this question might seem like a repetition, I have been tirelessly seeking a solution without success. The issue I am facing involves a method that resolves a promise only after the window has fully loaded. Subsequently, in my mounted h ...

Typescript-powered React component for controlling flow in applications

Utilizing a Control flow component in React allows for rendering based on conditions: The component will display its children if the condition evaluates to true, If the condition is false, it will render null or a specified fallback element. Description ...

What is the contrast between element.getAttribute() value and a String in protractor?

When using protractor and typescript, I need to verify that the text saved in a textbox matches a certain string by comparing it with the resulting value of element.getAttribute("value"). Unfortunately, getText() does not work for this scenario b ...

Is it considered proper to initialize an empty array within the data object of a Vue.js component?

For my component, I am in need of multiple empty arrays and predefined objects. The data object structure provided below seems to be effective for my purpose. However, I am uncertain if this is the optimal pattern and whether it might lead to unforeseen co ...

Instead of utilizing components, consider using multiple Vue instances for a more streamlined

I'm currently working on updating an old .NET MVC project that utilizes HTML, Bootstrap, and jQuery for its Views. I've decided to switch from jQuery to Vue.JS, but I'm struggling to determine the best approach. Since all the views are uniq ...

Issue 1068: Attribute not found within angular 2 (Ahead of Time Compilation)

I am currently learning Angular 2 and trying to create a "User Register" form. However, I encountered an error stating "Property does not exist on type" during Phone number validation. I am using both JIT and AOT compilers. With the JIT compiler, my user ...

Exploring the world of HTTP PUT requests in Angular 4.0

I have encountered an issue with a function I wrote for sending an http put request to update data. The function is not receiving any data: updateHuman(human: Human) { const url = `${this.url}/${human.id}`; const data = JSON.stringify(human); ...

Angular Error: Unable to access property 'users' on a null value

I am working on a component that takes in data through the @Input() decorator regarding a group. My objective is to generate a new array of objects during the initialization of the component based on the data from the group array. Below is the TypeScript c ...

Encountering an error with the Next Auth adapter in TypeScript when attempting to modify the default User interface

This is my first time using TypeScript and I am attempting to customize the default User interface for next-auth. I have experimented with the following code: next-auth.d.ts import { User } from "next-auth" import { JWT } from "next-auth/j ...

Detecting the specific number of digits before and after the decimal point in a Vuetify form number input can be achieved by utilizing

I am looking to only allow decimal and floating-point numbers as input. The restrictions are set to a maximum of 5 digits before the decimal point and a maximum of 2 digits after the decimal point. Initially, the rules were defined as follows: priceRules: ...

reactjs: disable a specific eslint rule

I'm trying to figure out how to disable the "no-unused-vars" rule specifically for TypeScript interfaces. Here's a code snippet where I'm getting a warning: export type IKeoTableColumn<T> = { id: T; align: 'left' | ' ...