如何解决在Vue 3和Typescript中使用globalProperties
我在main.ts中添加了一个全局属性,并试图在组件中访问它。但是我得到了错误:
Property '$const' does not exist on type 'ComponentPublicInstance<{},{},EmitsOptions,false,ComponentOptionsBase<{},ComponentOptionsMixin,string,{}>>'.Vetur(2339)
我认为我需要增加类型,打字稿现在认为$ 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>
任何帮助将不胜感激。
解决方法
我just answered有一个类似的问题,但在这里改述:
您可以在应用程序中扩充@vue/runtime-core
TypeScript模块:
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$const: Record<string,unknown>;
}
}
类似于Vue 2中的used to work。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。