TypeScript + vue3.0设置全局对象或者属性,出现ts类型错误.

时间:2025-03-05 07:30:12

需求:封装接口,将服务器接口的配置都放在了src/api文件下,在src/中添加全局api方便所有的组件都能访问到api。

问题:在/src/中设置了全局属性 .$api = api,但是报了ts类型必传的错误

参考链接:/guide/#%E4%B8%BA-globalproperties-%E6%89%A9%E5%85%85%E7%B1%BB%E5%9E%8B

解决办法:

src/types/。    若没有types文件夹则可以创建

import api from '@/api'
declare module '@vue/runtime-core' {
  export interface ComponentCustomProperties {
    $api: typeof api
  }
}

使用:例如在src/views/中使用api

import { getCurrentInstance } from "vue";
const app = getCurrentInstance();
// 通过app?.proxy?.$api就可以访问的到全局添加的api