vue3中如何實現定義全局變量
vue3定義全局變量
在vue2中,我們知道vue2.x是使用Vue.prototype.$xxxx=xxx來定義全局變量,然后通過this.$xxx來獲取全局變量。
但是在vue3中,這種方法顯然不行了。因為vue3中在setup里面我們是無法獲取到this的,因此按照官方文檔我們使用下面方法來定義全局變量:
首先在main.js里寫一個我們要定義的全局變量,比如一個系統(tǒng)id吧
app.config.globalProperties.$systemId = "10"
現在在頁面里需要使用這個變量,只需要從vue中引入getCurrentInstance即可,注意不能在頁面中使用this.
import { getCurrentInstance } from "vue";
const systemId = getCurrentInstance()?.appContext.config.globalProperties.$systemId
console.log(systemId);//控制臺可以看到輸出了10vue3全局變量app.config.globalProperties的使用
globalProperties
- 類型:[key: string]: any
- 默認:undefined
- 用法
添加一個可以在應用的任何組件實例中訪問的全局 property。組件的 property 在命名沖突具有優(yōu)先權。
這可以代替 Vue 2.x Vue.prototype 擴展:
// 之前(Vue 2.x)
Vue.prototype.$http = () => {}
?
// 之后(Vue 3.x)
const app = Vue.createApp({})
app.config.globalProperties.$http = () => {}當我們想在組件內調用http時需要使用getCurrentInstance()來獲取。
import { getCurrentInstance, onMounted } from "vue";
export default {
? setup( ) {
? ? const { ctx } = getCurrentInstance(); //獲取上下文實例,ctx=vue2的this
? ? onMounted(() => {
? ? ? console.log(ctx, "ctx");
? ? ? ctx.http();
? ? });
? },
};getCurrentInstance代表上下文,即當前實例。ctx相當于Vue2的this, 但是需要特別注意的是ctx代替this只適用于開發(fā)階段,如果將項目打包放到生產服務器上運行,就會出錯,ctx無法獲取路由和全局掛載對象的。此問題的解決方案就是使用proxy替代ctx,代碼參考如下。
import { getCurrentInstance } from 'vue'
export default ({
? name: '',
? setup(){
? ? const { proxy } = getCurrentInstance() // 使用proxy代替ctx,因為ctx只在開發(fā)環(huán)境有效
?? ?onMounted(() => {
? ? ? console.log(proxy, "proxy");
? ? ? proxy.http();
? ? });
? }
})注意:尤大在vue3推薦使用依賴注入:provide和inject。原因:vue/rfcs.
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

