Vue3組合式API之getCurrentInstance詳解
Vue2中,可以通過this來獲取當(dāng)前組件實例;
Vue3中,在setup中無法通過this獲取組件實例,console.log(this)打印出來的值是undefined。
在Vue3中,getCurrentInstance()可以用來獲取當(dāng)前組件實例 vue3官方文檔解釋
let { proxy } = getCurrentInstance();
在setup中分別打印下面3個值,結(jié)果如下:
console.log(getCurrentInstance,typeof(getCurrentInstance)); console.log(getCurrentInstance(),typeof(getCurrentInstance())); console.log(proxy,typeof(proxy));
可以看到,getCurrentInstance是一個function方法,getCurrentInstance()是一個對象,proxy也是一個對象。proxy是getCurrentInstance()對象中的一個屬性,通過對象的解構(gòu)賦值方式拿到proxy。
getCurrentInstance只能在setup或生命周期鉤子中使用。
1.在onMunted生命周期中打印getCurrentInstance
2.定義一個test方法,通過click事件觸發(fā)方法
onMounted(() => { console.log(getCurrentInstance(), typeof getCurrentInstance()); }); function test() { console.log(getCurrentInstance(), typeof getCurrentInstance()); }
可以看到在function中是無法獲取該實例的。
let { ctx } = getCurrentInstance(); console.log(ctx, typeof ctx); let { proxy } = getCurrentInstance(); console.log(proxy, typeof proxy);
ctx和proxy都是getCurrentInstance()對象中的屬性,通過解構(gòu)賦值的方式拿到??梢钥吹?,2者有所區(qū)別。ctx是普通對象,proxy是Proxy對象。
補充:Vue3中關(guān)于getCurrentInstance的大坑
開發(fā)中只適用于調(diào)試! 不要用于線上環(huán)境,否則會有問題!
解決方案:
方案1.
const instance = getCurrentInstance() console.log(instance.appContext.config.globalProperties)
獲取掛載到全局中的方法
方案2.
const { proxy } = getCurrentInstance()
使用proxy線上也不會出現(xiàn)問題
總結(jié)
到此這篇關(guān)于Vue3組合式API之getCurrentInstance詳解的文章就介紹到這了,更多相關(guān)Vue3組合式API getCurrentInstance內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解vue-Resource(與后端數(shù)據(jù)交互)
本篇文章主要介紹了vue-Resource(與后端數(shù)據(jù)交互),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01詳解vue3.2中setup語法糖<script?lang="ts"?setup>
Vue 3.2 引入了語法,這是一種稍微不那么冗長的聲明組件的方式,下面這篇文章主要介紹了詳解vue3.2中setup語法糖<script?lang="ts"setup>的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-01-01