在 Vue 3 和 Typescript 中使用 globalProperties [英] Using globalProperties in Vue 3 and Typescript

查看:357
本文介绍了在 Vue 3 和 Typescript 中使用 globalProperties的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've added a global property in main.ts, and am trying to access this in a component. however I'm getting the error:

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

我想我需要增加类型,打字稿现在认为 $const 是任何类型,但是我不知道如何在 Vue 3 中执行此操作,并且文档中没有提及.

I think I need to augment the type, typescript considers $const to be any type right now, however I don't know how to do this in Vue 3 and there is no mention in the docs.

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>

任何帮助将不胜感激.

推荐答案

刚刚回答一个类似的问题但会在此处转述:

I just answered a similar question but will paraphrase here:

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

You can augment the @vue/runtime-core TypeScript module in your application:

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

类似于 以前的工作方式 在 Vue 2 中.

similar to how this used to work in Vue 2.

检查ComponentCustomProperties 接口源代码了解更多信息.

Checkout the ComponentCustomProperties interface source code for more information.

这篇关于在 Vue 3 和 Typescript 中使用 globalProperties的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆