たとえば、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>