5月27日 01:06
Vue 3 如何在 setup 方法中获取组件实例?
Vue 3 Composition API 中,setup 里没有 this。要获取组件实例相关的能力,用对应的 API 而不是拿整个实例:
- 获取 DOM 元素:
const el = ref(null)+ref="el"绑定,通过el.value访问 - 获取路由实例:
const router = useRouter(); const route = useRoute() - 获取 store:
const store = useStore()(Pinia 或 Vuex 4) - 需要组件内部数据:直接在
setup里定义ref/reactive并 return,模板可直接访问 - 需要父组件数据:
defineProps+defineEmits
如果非拿实例不可(极少场景),Vue 3 提供了 getCurrentInstance():
javascriptimport { getCurrentInstance } from 'vue'; const instance = getCurrentInstance(); // instance.proxy 近似 Vue 2 的 this
但官方不推荐依赖它,内部实现在版本间可能变化。
追问
Vue 3 为什么不给 this?
Composition API 设计目标是函数式、可复用、类型推导友好。this 会绑定上下文,函数提取出去 this 就丢了。而 ref/reactive 是普通的 JS 值/对象,可以自由传递不丢失响应性。
template ref 和 document.getElementById 怎么选?
template ref 是 Vue 的方式——能保证在组件挂载后拿到元素,且不同组件实例互不干扰。document.getElementById 能拿到但可能拿到错误组件的元素(同页面多实例时),也不符合 Vue 的数据驱动理念。
getCurrentInstance 在 setup 外能用吗?
不能在 setup 外调用(如生命周期钩子的回调外)。它只在 setup 同步执行期间有效,异步回调里拿到的可能是 null。