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