欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3中如何實(shí)現(xiàn)定義全局變量

 更新時(shí)間:2022年07月21日 09:55:24   作者:想想就很棒  
這篇文章主要介紹了vue3中如何實(shí)現(xiàn)定義全局變量,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

vue3定義全局變量

在vue2中,我們知道vue2.x是使用Vue.prototype.$xxxx=xxx來定義全局變量,然后通過this.$xxx來獲取全局變量。

但是在vue3中,這種方法顯然不行了。因?yàn)関ue3中在setup里面我們是無(wú)法獲取到this的,因此按照官方文檔我們使用下面方法來定義全局變量:

首先在main.js里寫一個(gè)我們要定義的全局變量,比如一個(gè)系統(tǒng)id吧

app.config.globalProperties.$systemId = "10"

現(xiàn)在在頁(yè)面里需要使用這個(gè)變量,只需要從vue中引入getCurrentInstance即可,注意不能在頁(yè)面中使用this.

import { getCurrentInstance } from "vue";
const systemId = getCurrentInstance()?.appContext.config.globalProperties.$systemId
console.log(systemId);//控制臺(tái)可以看到輸出了10

vue3全局變量app.config.globalProperties的使用

globalProperties

  • 類型:[key: string]: any
  • 默認(rèn):undefined
  • 用法

添加一個(gè)可以在應(yīng)用的任何組件實(shí)例中訪問的全局 property。組件的 property 在命名沖突具有優(yōu)先權(quán)。

這可以代替 Vue 2.x Vue.prototype 擴(kuò)展:

// 之前(Vue 2.x)
Vue.prototype.$http = () => {}
?
// 之后(Vue 3.x)
const app = Vue.createApp({})
app.config.globalProperties.$http = () => {}

當(dāng)我們想在組件內(nèi)調(diào)用http時(shí)需要使用getCurrentInstance()來獲取。

import { getCurrentInstance, onMounted } from "vue";
export default {
? setup( ) {
? ? const { ctx } = getCurrentInstance(); //獲取上下文實(shí)例,ctx=vue2的this
? ? onMounted(() => {
? ? ? console.log(ctx, "ctx");
? ? ? ctx.http();
? ? });
? },
};

getCurrentInstance代表上下文,即當(dāng)前實(shí)例。ctx相當(dāng)于Vue2的this, 但是需要特別注意的是ctx代替this只適用于開發(fā)階段,如果將項(xiàng)目打包放到生產(chǎn)服務(wù)器上運(yùn)行,就會(huì)出錯(cuò),ctx無(wú)法獲取路由和全局掛載對(duì)象的。此問題的解決方案就是使用proxy替代ctx,代碼參考如下。

import { getCurrentInstance } from 'vue'
export default ({
? name: '',
? setup(){
? ? const { proxy } = getCurrentInstance() // 使用proxy代替ctx,因?yàn)閏tx只在開發(fā)環(huán)境有效
?? ?onMounted(() => {
? ? ? console.log(proxy, "proxy");
? ? ? proxy.http();
? ? });
? }
})

注意:尤大在vue3推薦使用依賴注入:provide和inject。原因:vue/rfcs.

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論