Vue3中g(shù)etCurrentInstance、頁(yè)面中route和router的獲取實(shí)現(xiàn)方式
getCurrentInstance、頁(yè)面中route和router的獲取方式
getCurrentInstance()
在vue2中,可以通過(guò)this來(lái)獲取組件實(shí)例,但是在vue3的setup函數(shù)中,無(wú)法通過(guò)this獲取到組件實(shí)例,在setup函數(shù)中this的值是undefined,但是vue3提供了getCurrentInstance()來(lái)獲取組件的實(shí)例對(duì)象;
const { ctx,proxy } = getCurrentInstance(); console.log(typeof getCurrentInstance); console.log(getCurrentInstance(), typeof getCurrentInstance()); console.log(proxy, typeof proxy); console.log(ctx, typeof ctx);
輸出結(jié)果:
可以看出,getCurrentInstance是一個(gè)方法,getCurrentInstance()是一個(gè)對(duì)象,ctx和proxy也是一個(gè)對(duì)象,ctx和proxy是getCurrentInstance()對(duì)象中的一個(gè)屬性,通過(guò)解構(gòu)賦值的方式拿到的,ctx是一個(gè)普通的對(duì)象,而proxy是一個(gè)proxy對(duì)象,兩者里面都可以看到當(dāng)前組件的data值和方法,可以使用proxy[屬性名]去獲取實(shí)例對(duì)象中的數(shù)據(jù)或者調(diào)用對(duì)象中的方法;
getCurrentInstance只能在setup函數(shù)或生命周期鉤子函數(shù)中使用;
ctx對(duì)象和proxy對(duì)象的區(qū)別:
1、從getCurrentInstance方法中解構(gòu)出來(lái)的ctx對(duì)象,只能在開(kāi)發(fā)環(huán)境下使用,生產(chǎn)環(huán)境下ctx將訪問(wèn)不到(不推薦使用)
2、proxy對(duì)象在開(kāi)發(fā)環(huán)境以及生產(chǎn)環(huán)境中都能拿到組件實(shí)例對(duì)象(推薦使用)
獲取組件實(shí)例對(duì)象的方式
1、獲取掛載到全局中的方法
const instance = getCurrentInstance() console.log(instance.appContext.config.globalProperties)
2、利用proxy對(duì)象
const { proxy } = getCurrentInstance()
獲取route和router的方式
- 方法一:通過(guò)getCurrentInstance()方法獲取到組件實(shí)例,從而獲取到route和router
import { getCurrentInstance } from "vue"; const { proxy } = getCurrentInstance(); proxy.$router.push({ path: "/home" }); // 實(shí)現(xiàn)路由跳轉(zhuǎn) console.log("獲取當(dāng)前路由---》", proxy.$route)
- 方法二:通過(guò)從vur-router中引入useRoute()、useRouter()方法來(lái)獲取到route和router
import { useRoute, useRouter } from 'vue-router' const router = useRouter(); const route = useRoute(); console.log('當(dāng)前路由:', route) router.push({ path: "/home" });
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue2移動(dòng)端+swiper實(shí)現(xiàn)異形的slide方式
這篇文章主要介紹了vue2移動(dòng)端+swiper實(shí)現(xiàn)異形的slide方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03解決vue動(dòng)態(tài)路由異步加載import組件,加載不到module的問(wèn)題
這篇文章主要介紹了解決vue動(dòng)態(tài)路由異步加載import組件,加載不到module的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07vue觸發(fā)真實(shí)的點(diǎn)擊事件跟用戶行為一致問(wèn)題
這篇文章主要介紹了vue觸發(fā)真實(shí)的點(diǎn)擊事件跟用戶行為一致問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03