方式一:使用依賴注入(provide/inject)(推薦)
在main.ts中進(jìn)行掛載:
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() (不推薦)
在main.ts中進(jìn)行掛載:
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>
vue 中的 getCurrentInstance 方法返回了 ctx 和 proxy,控制臺打印 ctx 和 proxy 發(fā)現(xiàn)和 vue2.x 中的 this 等同,習(xí)慣使用 this 的朋友可以用 proxy 進(jìn)行替代。
但是不推薦使用,不推薦原因其實在官網(wǎng)中已經(jīng)說的很明白了
官方解說: 在 setup() 內(nèi)部,this 不會是該活躍實例的引用(即不指向vue實例),因為 setup() 是在解析其它組件選項之前被調(diào)用的,所以 setup() 內(nèi)部的 this 的行為與其它選項中的 this 完全不同。這在和其它選項式 API 一起使用 setup() 時可能會導(dǎo)致混淆。因此setup函數(shù)中不能使用this。所以Vue為了避免我們錯誤的使用,直接將setup函數(shù)中的this修改成了 undefined)
我理解: 在Vue3中,setup 在生命周期 beforecreate 和 created 前執(zhí)行,此時 vue 對象還未創(chuàng)建,因此,無法使用我們在 vue2.x 常用的 this。在生產(chǎn)環(huán)境內(nèi)可能會獲取不到該實例!!,而且我們確實不應(yīng)該用該方法去代替this