在 vue 3 中获取子组件实例有两种方法:通过 ref 属性添加标识符,在父组件中使用 $refs 获取。通过 provide/inject api,在父组件中通过 provide() 提供数据,在子组件中通过 inject() 注入数据并返回子组件实例。
如何获取 Vue 3 子组件实例
在 Vue 3 中,有两种方式可以获取子组件实例:
1. 通过 ref 属性
- 在子组件上添加 ref 属性,指定一个唯一的标识符。
- 在父组件中,使用 $refs 对象获取子组件实例。
// 子组件 ChildComponent.vue
<template><div>我是子组件</div>
</template><script>
export default {
name: 'ChildComponent'
}
</script>
// 父组件 ParentComponent.vue
<template><child-component ref="child"></child-component></template><script>
export default {
mounted() {
const childInstance = this.$refs.child;
// childInstance 现在是 ChildComponent 实例
}
}
</script>
2. 通过 provide/inject API
立即学习“前端免费学习笔记(深入)”;
- 在父组件中通过 provide() 函数提供数据。
- 在子组件中通过 inject() 函数注入数据,同时返回子组件实例。
// 父组件 ParentComponent.vue
<template><child-component></child-component></template><script>
export default {
provide() {
return {
parentInstance: this
}
}
}
</script>
// 子组件 ChildComponent.vue
<template><div>我是子组件</div>
</template><script>
export default {
inject: ['parentInstance'],
mounted() {
// this.parentInstance 现在是 ParentComponent 实例
}
}
</script>