Vue3中关于getCurrentInstance的大坑怎么解决

其他教程   发布日期:2025年03月19日   浏览次数:219

本篇内容主要讲解“Vue3中关于getCurrentInstance的大坑怎么解决”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue3中关于getCurrentInstance的大坑怎么解决”吧!

解决方案

方案1.

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

获取挂载到全局中的方法

方案2.

  1. const { proxy } = getCurrentInstance()

使用proxy线上也不会出现问题

vue3核心之getCurrentInstance

vue3.x中的核心方法,用于访问实例上下文的router及vuex等

1、概述:一个很重要的方法,获取当前组件的实例、上下文来操作router和vuex等。

2、使用:由vue提供,按需引入:import { getCurrentInstance} from 'vue'

  1. import { getCurrentInstance } from 'vue';
  2. // 获取当前组件实例
  3. const instance = getCurrentInstance();
  4. // 获取当前组件的上下文,下面两种方式都能获取到组件的上下文。
  5. const { ctx } = getCurrentInstance(); // 方式一,这种方式只能在开发环境下使用,生产环境下的ctx将访问不到
  6. const { proxy } = getCurrentInstance(); // 方式二,此方法在开发环境以及生产环境下都能放到组件上下文对象(推荐)
  7. // ctx 中包含了组件中由ref和reactive创建的响应式数据对象,以及以下对象及方法;
  8. proxy.$attrs
  9. proxy.$data
  10. proxy.$el
  11. proxy.$emit
  12. proxy.$forceUpdate
  13. proxy.$nextTick
  14. proxy.$options
  15. proxy.$parent
  16. proxy.$props
  17. proxy.$refs
  18. proxy.$root
  19. proxy.$slots
  20. proxy.$watch

以上就是Vue3中关于getCurrentInstance的大坑怎么解决的详细内容,更多关于Vue3中关于getCurrentInstance的大坑怎么解决的资料请关注九品源码其它相关文章!