在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 {};