vue3的getCurrentInstance获取当前组件实例

vue3的setup中没有this时需要使用getCurrentInstance()来获取。

在 Vue 3 中,getCurrentInstance 方法可以在组合式 API(Composition API)中获取当前组件实例。这个方法返回一个包含了组件实例的对象,你可以用它来访问组件的 props、attrs、slots 和 emit 方法等。

proxy:访问响应式数据和方法
ctx:访问属性和方法
注:ctx代替this只适用于开发阶段,如果将项目打包放到生产服务器上运行,就会出错,ctx无法获取路由和全局挂载对象的。此问题的解决方案就是使用proxy替代ctx

举例:
1、如果说我们要通过$refs来获取dom。

<script setup>
  import { getCurrentInstance, onMounted } from "vue";

  const {proxy,ctx } = getCurrentInstance();

  onMounted(()=>{
    console.log(proxy.$refs.test_ref,ctx.$refs.test_ref)
  })
</script>

<template>
  <div>
    <div ref="test_ref">$refs获取</div>
  </div>
</template>

在这里插入图片描述
2、全局导入api接口方便使用
一个用于注册能够被应用内所有组件实例访问到的全局属性的对象
vue2的main.js

import api from './api' // 导入api接口
Vue.prototype.$api = api

页面上使用时:

this.$api

globalProperties是对 Vue 2 中 Vue.prototype 使用方式的一种替代,如果全局属性与组件自己的属性冲突,组件自己的属性将具有更高的优先级。
vue3的main.js

import api from './api'
app.config.globalProperties.api = api

页面上使用时:

import { getCurrentInstance, onMounted } from "vue";
const {proxy,ctx } = getCurrentInstance();
 onMounted(()=>{
   console.log(proxy.api)
 })

在这里插入图片描述

  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值