行业知识
Vue3使用全局函数或变量的两种常用方式
2026-11-16 18:50:14
来源:互联网转载
���如:想要在index.ts中创建getAction函数,并可以全局使用:
()import { http } from '@/utils/axios'export function getAction (url: string, params: object) { return http.request({ url: url, method: 'get', params: params })} 方式一:使用依赖注入(provide/inject)
在main.ts中进行挂载:
()import { createApp } from 'vue'import App from './App.vue'const app = createApp(App)import { getAction } from 'index'app.provide('getAction', getAction) // 将getAction方法挂载到全局app.mount('#app') 在要使用的页面注入:
import { inject } from 'vue'const getAction: any = inject('getAction') 方式二:使用 app.config.globalProperties 和 getCurrentInstance()
- app.config.globalProperties:一个用于注册能够被应用内所有组件实例访问到的全局属性的对象
- getCurrentInstance():// 获取当前实例,类似于vue2的this
import { createApp } from 'vue'import App from './App.vue'const app = createApp(App)import { getAction } from 'index'app.config.globalProperties.$getAction = getActionapp.mount('#app')在要使用的页面中使用:
import { getCurrentInstance } from 'vue'const { proxy }: any = getCurrentInstance()console.log('proxy:', proxy)console.log('getAction:', proxy.$getAction)