vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue3中getCurrentInstance、页面route和router获取方式

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

作者:熬夜胡萝北

这篇文章主要介绍了Vue3中getCurrentInstance、页面中route和router的获取实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

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的方式

import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
proxy.$router.push({ path: "/home" });  // 实现路由跳转
console.log("获取当前路由---》", proxy.$route)
import { useRoute, useRouter } from 'vue-router'
const router = useRouter();
const route = useRoute();
console.log('当前路由:', route)
router.push({ path: "/home" });

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文