Vue3使用全局函數(shù)或變量的2種常用方式代碼
更新時間:2023年09月21日 11:19:47 作者:theMuseCatcher
在Vue3項目中需要頻繁使用某一個方法,配置到全局感覺會方便很多,這篇文章主要給大家介紹了關(guān)于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中進行掛載:
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()
- app.config.globalProperties:一個用于注冊能夠被應(yīng)用內(nèi)所有組件實例訪問到的全局屬性的對象
- getCurrentInstance():// 獲取當前實例,類似于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')在要使用的頁面中使用:
<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ù)或變量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue設(shè)置全局變量5種方法(讓你的數(shù)據(jù)無處不在)
這篇文章主要給大家介紹了關(guān)于vue設(shè)置全局變量的5種方法,通過設(shè)置的方法可以讓你的數(shù)據(jù)無處不在,在項目中經(jīng)常會復(fù)用一些變量和函數(shù),比如用戶的登錄token,用戶信息等,這時將它們設(shè)為全局的就顯得很重要了,需要的朋友可以參考下2023-11-11

