前端[vue3.0] tyepescript+vue3使用全局变量后的类型提示解决方式

321 阅读1分钟

我们在使用vue3.0+typescript开发时经常需要在globalProperties中添加全局函数,但是我们添加完这个变量后如何对这个变量做类型提示呢?今天我们就以如下代码来做类型提示的尝试。

如下所示,我们在config.globalProperties添加了一个变量$costumeVal

import { createApp } from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";
import store from "./store";

const app = createApp(App);
app.config.globalProperties.$costumeVal = "自定义变量";
app.use(store).use(router);
app.mount("#app");

ctx?.appContext.config.globalProperties类型提示

我们在使用的时候一般通过如下方式使用

image.png

<template>
  <div class="home">
    <h1>
      $costumeVal: {{ ctx?.appContext.config.globalProperties.$costumeVal }}
    </h1>
  </div>
</template>
<script setup lang="ts">
import { getCurrentInstance } from "vue";
const ctx = getCurrentInstance();
</script>

但是这种声明给出的提示确是 any

image.png

类型修复

对此我们需要对该类型进行修复,修复的方式就是在vue类型模块中重写,代码如下所示

每个组件的实例化context对应一个ComponentCustomProperties自定义原型类型提示,我们需要自己实现这个接口类型,并覆盖原有的声明。

image.png

此时我们进入刚刚的组件,输入appContext.config.就会发现已经有类型提示了,同时也给出了正确的类型

image.png

image.png

image.png 同时页面上也正确显示了该内容

image.png

疑问

为什么定义在 @vue/runtime-core中的类型能够被正确解析,而定义在其它地方的组件就会报错呢?

我们打开node_modules/@vue/runtime-core/dist/runtime-core.d.ts文件,我们发现这个类型文件所导出的数据都是vue运行时所使用的各种属性定义和钩子函数,如下代码片段

image.png

在这个文件中我们发现了这样一段代码,ComponentCustomProperties这段代码就是:自定义属性以任何方式添加到组件实例中,并且可以通过' this '访问。而且给出了示例代码。

image.png