在 Vue3 中获取组件实例的方法取决于你的使用场景(组合式 API 或选项式 API)以及是否需要获取当前组件实例或子组件实例。以下是常见方法:
一、获取当前组件实例
1. 组合式 API(<script setup>
或 setup()
)
- 不推荐直接获取实例,但可通过
getCurrentInstance
方法(通常用于高级场景):
⚠️ 注意:<script setup> import { getCurrentInstance } from 'vue' const instance = getCurrentInstance() // 通过 instance.proxy 访问组件实例的公开属性 console.log(instance.proxy.$el) // 根 DOM 元素 console.log(instance.proxy.$data) // 组件数据
getCurrentInstance
主要用于库开发,官方不建议在业务代码中直接依赖它。优先使用响应式 API(如ref
、reactive
)和props
/emit
。
2. 选项式 API
- 直接通过
this
访问当前实例:<script> export default { methods: { myMethod() { console.log(this.$el) //