Vue3에서 전역 함수 또는 변수를 사용하는 두 가지 일반적인 방법

예: index.ts에 getAction 함수를 생성하고 전역적으로 사용하고 싶습니다.

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

방법 1: 종속성 주입 사용(제공/주입)

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

사용할 페이지에 삽입:

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

방법 2: app.config.globalProperties 및 getCurrentInstance() 사용

  • app.config.globalProperties: 애플리케이션의 모든 구성 요소 인스턴스에서 액세스할 수 있는 전역 속성을 등록하는 데 사용되는 개체입니다.
  • getCurrentInstance(): // 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')

 사용하려는 페이지에서:

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

추천

출처blog.csdn.net/Dandrose/article/details/129302786