Vue3使用全局函數(shù)或變量的2種常用方式代碼
例如:想要在index.ts中創(chuàng)建getAction函數(shù),并可以全局使用:
import { http } from '@/utils/axios'
export function getAction (url: string, params: object) {
return http.request({
url: url,
method: 'get',
params: params
})
}方式一:使用依賴注入(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()
- app.config.globalProperties:一個(gè)用于注冊(cè)能夠被應(yīng)用內(nèi)所有組件實(shí)例訪問(wèn)到的全局屬性的對(duì)象
- getCurrentInstance():// 獲取當(dāng)前實(shí)例,類(lèi)似于vue2的this
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')在要使用的頁(yè)面中使用:
<script setup lang="ts">
import { getCurrentInstance } from 'vue'
const { proxy }: any = getCurrentInstance()
console.log('proxy:', proxy)
console.log('getAction:', proxy.$getAction)
</script>總結(jié)
到此這篇關(guān)于Vue3使用全局函數(shù)或變量的2種常用方式的文章就介紹到這了,更多相關(guān)Vue3使用全局函數(shù)或變量?jī)?nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue實(shí)現(xiàn)用戶登錄及token驗(yàn)證
這篇文章主要為大家詳細(xì)介紹了Vue實(shí)現(xiàn)用戶登錄及token驗(yàn)證,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
Vue3滑動(dòng)到最右驗(yàn)證功能實(shí)現(xiàn)
在登錄頁(yè)面需要啟動(dòng)向右滑塊驗(yàn)證功能,遇到這樣的需求怎么實(shí)現(xiàn)呢,下面小編通過(guò)示例代碼給大家分享Vue3滑動(dòng)到最右驗(yàn)證功能實(shí)現(xiàn),感興趣的朋友一起看看吧2024-06-06
vue設(shè)置全局變量5種方法(讓你的數(shù)據(jù)無(wú)處不在)
這篇文章主要給大家介紹了關(guān)于vue設(shè)置全局變量的5種方法,通過(guò)設(shè)置的方法可以讓你的數(shù)據(jù)無(wú)處不在,在項(xiàng)目中經(jīng)常會(huì)復(fù)用一些變量和函數(shù),比如用戶的登錄token,用戶信息等,這時(shí)將它們?cè)O(shè)為全局的就顯得很重要了,需要的朋友可以參考下2023-11-11

