• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

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

    发布者: 网神之王 | 发布时间: 2025-6-14 15:31| 查看数: 90| 评论数: 0|帖子模式

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


    getCurrentInstance()

    在vue2中,可以通过this来获取组件实例,但是在vue3的setup函数中,无法通过this获取到组件实例,在setup函数中this的值是undefined,但是vue3提供了getCurrentInstance()来获取组件的实例对象;
    1.     const { ctx,proxy } = getCurrentInstance();
    2.     console.log(typeof getCurrentInstance);
    3.     console.log(getCurrentInstance(), typeof getCurrentInstance());
    4.     console.log(proxy, typeof proxy);
    5.     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. const instance = getCurrentInstance()
    2. console.log(instance.appContext.config.globalProperties)
    复制代码
    2、利用proxy对象
    1. const { proxy } = getCurrentInstance()  
    复制代码
    获取route和router的方式


    • 方法一:通过getCurrentInstance()方法获取到组件实例,从而获取到route和router
    1. import { getCurrentInstance } from "vue";
    2. const { proxy } = getCurrentInstance();
    3. proxy.$router.push({ path: "/home" });  // 实现路由跳转
    4. console.log("获取当前路由---》", proxy.$route)
    复制代码

    • 方法二:通过从vur-router中引入useRoute()、useRouter()方法来获取到route和router
    1. import { useRoute, useRouter } from 'vue-router'
    2. const router = useRouter();
    3. const route = useRoute();
    4. console.log('当前路由:', route)
    5. router.push({ path: "/home" });
    复制代码
    总结

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

    来源:https://www.jb51.net/javascript/339886jmp.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有账号?立即注册

    ×

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表