在ts中约束 getCurrentInstance 类型

532 阅读1分钟

main.ts中往全局属性挂载了一些方法,比如:

import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);

// 挂载
app.config.globalProperties.$message = (msg: string) => {
  return 'this is global message'
};

在组件中使用的时候,ts推导不出来

<template>
  <button type="button" @click="getUserInfo">{{ $message('小明') }}}</md-button>
</template>

<script lang="ts" setup>
const vm = getCurrentInstance();

async function getUserInfo() {
  console.log('appContext', vm?.proxy?.$message);
}
</script>

解决方式:

/src/module.d.ts先声明好自己加的属性或者方法

declare module '@vue/runtime-core' {
  export interface ComponentCustomProperties {
    $message: (msg: string) => string;
  }
}
export {};