vue3使用getCurrentInstance线上环境报错问题

本文详细介绍了在Vue3中如何使用getCurrentInstance访问内部组件实例,以及在开发和线上环境中遇到的问题。尽管Vue3官方不推荐在应用代码中直接使用getCurrentInstance,但在特定场景下,它仍然是必要的。文章提到了在开发环境利用getCurrentInstance获取实例正常,但在线上环境会导致错误,建议使用proxy替代,并展示了如何解构proxy来获取实例。同时,文中还对比了使用ctx访问组件实例的方式。

getCurrentInstance 支持访问内部组件实例。
vue3官网中提示:getCurrentInstance 只暴露给高阶使用场景,典型的比如在库中。强烈反对在应用的代码中使用 getCurrentInstance。请不要把它当作在组合式 API 中获取 this 的替代方案来使用。

在开发环境下使用getCurrentInstance的ctx获取实例没有问题,但是在线上环境会报错,建议使用proxy代替,使用时直接将proxy解构出来
在这里插入图片描述
在这里插入图片描述

线上环境具体代码如下:

<script setup>
import { onMounted, nextTick, getCurrentInstance } from 'vue'
// 当前实例对象
let currentInstance = ''
// 初始化
onMounted(()=>{
  currentInstance = getCurrentInstance()
  nextTick(()=>{
    drawWidth.value = currentInstance.proxy.$refs['canvasMain'].offsetWidth;
  })
})
</script>

使用ctx示例:

<script setup>
import { onMounted, nextTick, getCurrentInstance } from 'vue'
// 当前实例对象
let currentInstance = ''
// 初始化
onMounted(()=>{
  currentInstance = getCurrentInstance()
  nextTick(()=>{
    drawWidth.value = currentInstance.ctx.$refs.canvasMain.offsetWidth;
  })
})
</script>

参考博客:https://blog.csdn.net/SmartJunTao/article/details/124878135

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值