欢迎来到科站长!

JavaScript

当前位置: 主页 > 网络编程 > JavaScript

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

时间:2025-07-25 09:57:09|栏目:JavaScript|点击:

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

getCurrentInstance()

在vue2中,可以通过this来获取组件实例,但是在vue3的setup函数中,无法通过this获取到组件实例,在setup函数中this的值是undefined,但是vue3提供了getCurrentInstance()来获取组件的实例对象;

1
2
3
4
5
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、获取挂载到全局中的方法

1
2
const instance = getCurrentInstance()
console.log(instance.appContext.config.globalProperties)

2、利用proxy对象

1
const { proxy } = getCurrentInstance()

获取route和router的方式

  • 方法一:通过getCurrentInstance()方法获取到组件实例,从而获取到route和router
1
2
3
4
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
proxy.$router.push({ path: "/home" });  // 实现路由跳转
console.log("获取当前路由---》", proxy.$route)
  • 方法二:通过从vur-router中引入useRoute()、useRouter()方法来获取到route和router
1
2
3
4
5
import { useRoute, useRouter } from 'vue-router'
const router = useRouter();
const route = useRoute();
console.log('当前路由:', route)
router.push({ path: "/home" });


上一篇:原生JS实现HTML转Markdown功能

栏    目:JavaScript

下一篇:JavaScript使用docx-preview和mammoth预览Docx

本文标题:Vue3中getCurrentInstance、页面中route和router的获取实现方式

本文地址:https://www.fushidao.cc/wangluobiancheng/23777.html

广告投放 | 联系我们 | 版权申明

申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:257218569 | 邮箱:257218569@qq.com

Copyright © 2018-2025 科站长 版权所有冀ICP备14023439号