vue3中getCurrentInstance怎么使用

父组件中:

1.setup语法糖中导入子组件

2.在子组件标签上绑定ref值

3.setup内部从vue中按需导出 getCurrentInstance 方法

4.调用getCurrentInstance方法导出proxy

5.通过proxy.$refs.子组件ref名.子组件内属性/方法 实现调用

立即学习“前端免费学习笔记(深入)”;

    
              
 import { getCurrentInstance, ComponetInternalInstance,ref } from "vue";import Child from "./zi.vue";const child = ref(null) // as ComponetInternalInstance表示类型断言,ts时使用。否则报错,proxy为nullconst { proxy } = getCurrentInstance() as ComponetInternalInstance;function changeChildren() { proxy.$refs.child.count += 1; //也可以使用ref数据.value的形式调用: //child.value.count += 1 console.log(child.value.name)} 

登录后复制

main.js

import api from "./utils/api.js"import StringUtil from "./utils/StringUtil.js"app.config.globalProperties.api = api;app.config.globalProperties.StringUtil = StringUtil;

登录后复制

import {getCurrentInstance } from 'vue';const { proxy } = getCurrentInstance();console.log(proxy.api);console.log(proxy.StringUtil.isBlank('1'));

登录后复制

方式一、通过 getCurrentInstance 方法获取当前组件实例,从而获取 route 和 router

Html

  
  
import { defineComponent, getCurrentInstance } from 'vue'export default defineComponent({ name: 'About', setup(){ const { proxy } = getCurrentInstance() console.log(proxy.$root.$route) console.log(proxy.$root.$router) return {} }})

登录后复制

方式二:通过从路由中导入 useRoute useRouter 使用 route 和 router。

Html

import { defineComponent } from ‘vue'import { useRoute, useRouter } from ‘vue-router'export default defineComponent({setup () {const $route = useRoute()const r o u t e r = u s e R o u t e r ( ) c o n s o l e . l o g ( router = useRouter() console.log(router=useRouter()console.log(route)console.log($router)}})

登录后复制

附:Vue3中关于getCurrentInstance的大坑

开发中只适用于调试! 不要用于线上环境,否则会有问题!

解决方案:

方案1.

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

登录后复制

获取挂载到全局中的方法

方案2.

const { proxy } = getCurrentInstance()

登录后复制

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

以上就是vue3中getCurrentInstance怎么使用的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/3229988.html

(0)
上一篇 2025年4月1日 16:25:10
下一篇 2025年4月1日 16:25:21

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论