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