0


Vue3——getCurrentInstance、页面中route和router的获取方式

getCurrentInstance()

在vue2中,可以通过this来获取组件实例,但是在vue3的setup函数中,无法通过this获取到组件实例,在setup函数中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);

输出结果:

可以看出,getCurrentInstance是一个方法,getCurrentInstance()是一个对象,ctx和proxy也是一个对象,ctx和proxy是getCurrentInstance()对象中的一个属性,通过解构赋值的方式拿到的,ctx是一个普通的对象,而proxy是一个proxy对象,两者里面都可以看到当前组件的data值和方法,可以使用proxy[属性名]去获取实例对象中的数据或者调用对象中的方法;

getCurrentInstance只能在setup函数或生命周期钩子函数中使用;

ctx对象和proxy对象的区别:

1、从getCurrentInstance方法中解构出来的ctx对象,只能在开发环境下使用,生产环境下ctx将访问不到(不推荐使用)

2、proxy对象在开发环境以及生产环境中都能拿到组件实例对象(推荐使用)

获取组件实例对象的方式

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.$root.$router.push({ path: "/home" });  // 实现路由跳转

方法二:通过从vur-router中引入useRouter()方法来获取到route和router

import { useRouter } from 'vue-router'
const router = useRouter();
router.push({ path: "/home" });

本文转载自: https://blog.csdn.net/m0_46318298/article/details/130726043
版权归原作者 一颗熬夜的胡萝北 所有, 如有侵权,请联系我们删除。

“Vue3——getCurrentInstance、页面中route和router的获取方式”的评论:

还没有评论