Two common ways for Vue3 to use global functions or variables

For example: want to create a getAction function in index.ts and use it globally:

import { http } from '@/utils/axios'
export function getAction (url: string, params: object) {
  return http.request({
    url: url,
    method: 'get',
    params: params
  })
}

Method 1: Use dependency injection (provide/inject)

Mount in 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')

Inject in the page to use:

<script setup lang="ts">
import { inject } from 'vue'
const getAction: any = inject('getAction')
</script>

Method 2: Use app.config.globalProperties and getCurrentInstance()

  • app.config.globalProperties: An object used to register global properties that can be accessed by all component instances in the application
  • getCurrentInstance(): // Get the current instance, similar to this of vue2
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)
import { getAction } from 'index'
app.config.globalProperties.$getAction = getAction

app.mount('#app')

 In the page you want to use:

<script setup lang="ts">
import { getCurrentInstance } from 'vue'
const { proxy }: any = getCurrentInstance()
console.log('proxy:', proxy)
console.log('getAction:', proxy.$getAction)
</script>

Guess you like

Origin blog.csdn.net/Dandrose/article/details/129302786