typescript - 从 Vue 组件中的 index.html 获取全局窗口变量

标签 typescript vue.js stenciljs

如果我有一个 Stencil.js 组件,我像这样加载到我的 Vue 项目中:

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>

然后我想访问我的 vue 组件中的顶栏信息。 类似的东西

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>

所以在这里我希望我的顶部栏中的所有内容都可以在我的 Vue 组件中访问。 现在,如果我打开 Chrome devtools,我可以编写 topbar.user 并获取用户的所有信息,但我也希望所有 vue 组件都可以访问这些信息。

最佳答案

问题是 TypeScript 不知道该属性。您可以通过多种方式解决这个问题:

  1. 在上一行添加//@ts-ignore。这会抑制下一行的错误。
  2. 转换为任意:(窗口为任意).topbar
  3. Define the propertywindow界面中:
declare global {
    interface Window { topbar: any; }
}

关于typescript - 从 Vue 组件中的 index.html 获取全局窗口变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60100274/

相关文章:

javascript - Angular CLI 类文件导入必须大写——为什么?

javascript - 如何使用 Rollup 将本地 typescript 文件捆绑到主包中

Vue.js 一些错误/警告很难调试

vue.js 注册 webcomponent

javascript - Stenciljs @Method 不工作

javascript - StencilJs 组件未在另一个 stenciljs 项目中呈现

typescript - 错误 : The typescript task detection didn't contribute a task for the following configuration

javascript - 反转数组,保持原始顺序

javascript - vuejs方法中的Parseint

web-component - Stencil JS - 如何分发一组共享方法