ts环境下vue3全局变量的声明和使用

在vue2中全局变量是prototype

在vue3中使用globalProperties
比如引入elementPlus的组件作为全局变量

1、在main.ts中声明

import * as ElIcons from '@element-plus/icons'
import * as ElementUI from 'element-plus'

const app =createApp(APP)
for(const name in ElIcons) {
  app.component(name, (ElIcons as any))
}
app.use(router).use(store,key).mountt('#app')

// 声明全局变量属性
declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
     $confirm: (a:string) => Promise<void>
     $Alert: (a:string) => Promise<void>
     $Notify: (a:string) => Promise<void>
 }
}

// 声明全局变量
app.config.globalProperties.$Alert = ElementUI.ElMessageBox.alert 
app.config.globalProperties.$Confirm = ElementUI.ElMessageBox.confirm
app.config.globalProperties.$Notify = ElementUI.ElNotification

2、在组件中使用声明的全局变量
报错很好理解 因为 getCurrentInstance() 的返回类型存在 null 所以在此处添加断言即可

<template>
  <div>
    <el-button @click="add">点击</el-button>
  </div>
</template>

// 说明:如果element-ui组件是自动按需引入,则需要单独引入css,文件
import 'element-plus/es/components/message-box/style/css'
import { ComponentInternalInstance, getCurrentInstance } from 'vue';
// 添加断言
const { proxy } =  getCurrentInstance() as ComponentInternalInstance

const add = () => {
  // 使用as定义数据类型,还需要使用proxy?.来排除null
  proxy?.$Alert('哇哈哈')
}
posted @   小鱼儿-xy  阅读(3292)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示