【问题标题】:Using globalProperties in Vue 3 and Typescript在 Vue 3 和 Typescript 中使用 globalProperties
【发布时间】:2021-01-18 09:04:52
【问题描述】:

我在 main.ts 中添加了一个全局属性,并试图在组件中访问它。但是我收到了错误:

Property '$const' does not exist on type 'ComponentPublicInstance<{}, {}, {}, {}, {}, EmitsOptions, {}, {}, false, ComponentOptionsBase<{}, {}, {}, {}, {}, ComponentOptionsMixin, ComponentOptionsMixin, EmitsOptions, string, {}>>'.Vetur(2339)

我认为我需要增加类型,typescript 现在认为 $const 是任何类型,但是我不知道如何在 Vue 3 中执行此操作,文档中也没有提及。

main.ts

import { createApp } from "vue";
import App from "./App.vue";
import store from "./store";
import * as constants from "@constants";

const app = createApp(App);

app.config.globalProperties.$const = Object.freeze(constants);

app.use(store);

app.mount("#app");

组件

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Header",

  computed: {
    tags() {
      return Object.entries(this.$const.TAGS);
    }
  }
});
</script>

任何帮助将不胜感激。

【问题讨论】:

    标签: typescript vuejs3 vetur


    【解决方案1】:

    just answered 有一个类似的问题,但会在此处转述:

    您可以在应用程序中扩充@vue/runtime-core TypeScript 模块:

    declare module '@vue/runtime-core' {
      interface ComponentCustomProperties {
        $const: Record<string, unknown>;
      }
    }
    

    类似于 Vue 2 中的 used to work

    查看ComponentCustomProperties interface source code 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2021-04-15
      • 2021-12-17
      • 2021-04-19
      • 1970-01-01
      • 2022-12-10
      • 2019-04-19
      • 2021-10-10
      • 2021-09-11
      • 2023-02-07
      相关资源
      最近更新 更多