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():// 獲取當(dāng)前實例,類似于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中使用vue-count-to(數(shù)字滾動插件)詳細教程
這篇文章主要給大家介紹了關(guān)于Vue中使用vue-count-to(數(shù)字滾動插件)的相關(guān)資料,最近需要開發(fā)一個數(shù)字滾動效果,在網(wǎng)上找到一個關(guān)于vue-countTo的插件,覺得這個插件還不錯,需要的朋友可以參考下2023-09-09
element-plus中el-upload組件限制上傳文件類型的方法
?Element Plus 中,el-upload 組件可以通過設(shè)置 accept 屬性來限制上傳文件的格式,這篇文章主要介紹了element-plus中el-upload組件限制上傳文件類型,需要的朋友可以參考下2024-02-02
vue3.0使用mapState,mapGetters和mapActions的方式
這篇文章主要介紹了vue3.0使用mapState,mapGetters和mapActions的方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
Vue公共loading升級版解決思路(處理并發(fā)異步差時響應(yīng))
這篇文章主要介紹了Vue公共loading升級版(處理并發(fā)異步差時響應(yīng)),解決思路是通過定義一個全局對象來存儲每個接口的響應(yīng)狀態(tài),直到每個請求接口都收到響應(yīng)才變更狀態(tài),結(jié)束loading動畫,需要的朋友可以參考下2023-11-11
詳解VUE Element-UI多級菜單動態(tài)渲染的組件
這篇文章主要介紹了VUE Element-UI多級菜單動態(tài)渲染的組件,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04

