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

被折叠的 条评论
为什么被折叠?



