TypeScript + vue3.0设置全局对象或者属性,出现ts类型错误.
需求:封装接口,将服务器接口的配置都放在了src/api文件下,在src/main.js中添加全局api方便所有的组件都能访问到api。问题:在/src/main.js中设置了全局属性 app.config.globalProperties.$api = api,但是报了ts类型必传的错误参考链接:https://v3.cn.vuejs.org/guide/typescript-support.h
·
需求:封装接口,将服务器接口的配置都放在了src/api文件下,在src/main.js中添加全局api方便所有的组件都能访问到api。
问题:在/src/main.js中设置了全局属性 app.config.globalProperties.$api = api,但是报了ts类型必传的错误
参考链接:https://v3.cn.vuejs.org/guide/typescript-support.html#%E4%B8%BA-globalproperties-%E6%89%A9%E5%85%85%E7%B1%BB%E5%9E%8B
解决办法:
src/types/api.d.ts。 若没有types文件夹则可以创建
import api from '@/api'
declare module '@vue/runtime-core' {
export interface ComponentCustomProperties {
$api: typeof api
}
}
使用:例如在src/views/LoginPage.vue中使用api
import { getCurrentInstance } from "vue";
const app = getCurrentInstance();
// 通过app?.proxy?.$api就可以访问的到全局添加的api
更多推荐
已为社区贡献1条内容
所有评论(0)