问题:vue3中 自定义/封装 的全局可用的数据与方法,怎么在全局使用?
一、实际情况
在 src/utils 下封装了全局可用的 自定义校验规则(Verify.js) 与 Message 消息提(Message.js),想要把它们注册到全局都可调用的状态,该怎么做呢?
二、实际操作
1、在 main.js/main.ts 中引入该方法/组件/数据:
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 全局组件
import Dialog from './components/Dialog.vue'
// 全局方法
import Verify from '@/utils/Verify.js'
import Message from '@/utils/Message.js'
app.config.globalProperties.globalInfo = { bodyWidth: 1300 } // 全局可用数据
app.config.globalProperties.Verify = Verify // 全局可用方法
app.config.globalProperties.Message = Message // 全局可用方法
app.component('Dialog', Dialog) // 全局可用组件
2、方法/组件/数据 的使用
2.1 组件 直接app.component('Dialog', Dialog) 的 Dialog 即可
2.2 方法、数据
getCurrentInstance代表上下文,即当前实例,使用 proxy 做代理,即可使用 proxy 调用 全局注册 的方法
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
方法的使用
数据的使用