vue3挂载全局方法
方式一:使用依赖注入(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')
在要使用的页面注入:
<script setup lang="ts"> import { inject } from 'vue' const getAction: any = inject('getAction') </script>
方式二:使用 app.config.globalProperties 和 getCurrentInstance()
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>