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 @ 2023-03-05 12:21  小鱼儿-xy  阅读(3536)  评论(0)    收藏  举报