在 Vue 3 中获取子组件实例有两种方法:通过 ref 属性添加标识符,在父组件中使用 $refs 获取。通过 provide/inject API,在父组件中通过 provide() 提供数据,在子组件中通过 inject() 注入数据并返回子组件实例。

如何获取 Vue 3 子组件实例
在 Vue 3 中,有两种方式可以获取子组件实例:
1. 通过 ref 属性
ref 属性,指定一个唯一的标识符。$refs 对象获取子组件实例。<code class="js">// 子组件 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></code>2. 通过 provide/inject API
立即学习“前端免费学习笔记(深入)”;
provide() 函数提供数据。inject() 函数注入数据,同时返回子组件实例。<code class="js">// 父组件 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></code>以上就是vue3怎么获取子组件实例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号