在 Vue 3 中,获取子组件实例的方法有所变化。在 Vue 2 中,我们可以通过"$children"属性来获取子组件实例,然后再进行访问子组件的方法。而在 Vue 3 中,我们需要使用"ref"或"reactive"来创建一个响应式引用,然后再通过"toRefs"函数将其转换为普通对象,通过这个对象来访问子组件的方法。\n\n让我们来看一个示例:\n\nvue\n<template>\n <div>\n <ChildComponent ref="childComponentRef" />\n <button @click="callChildMethod">调用子组件方法</button>\n </div>\n</template>\n\n<script>\nimport { ref, toRefs } from 'vue';\nimport ChildComponent from './ChildComponent.vue';\n\nexport default {\n components: {\n ChildComponent\n },\n setup() {\n const childComponentRef = ref(null);\n\n // 获取子组件实例\n const getChildComponentInstance = () => {\n return childComponentRef.value;\n };\n\n // 调用子组件方法\n const callChildMethod = () => {\n const childComponent = getChildComponentInstance();\n childComponent.childMethod(); // 调用子组件的方法\n };\n\n return {\n childComponentRef,\n callChildMethod\n };\n }\n};\n</script>\n\n\n在上面的示例中,我们使用"ref"来创建一个响应式引用"childComponentRef",然后将其赋值给子组件的"ref"属性。在父组件的"setup"函数中,我们定义了一个"getChildComponentInstance"函数,用于获取子组件实例。然后,在"callChildMethod"函数中,我们通过"getChildComponentInstance"函数获取子组件实例,并调用子组件的"childMethod"方法。\n\n需要注意的是,子组件的"childMethod"方法需要在子组件中进行导出,父组件才能访问到该方法。所以,在子组件中需要进行如下导出:\n\njavascript\nexport default {\n methods: {\n childMethod() {\n // 子组件方法的实现\n }\n }\n};\n\n\n这样,父组件就能够获取到子组件的实例,并调用子组件的方法了。

Vue 3 获取子组件实例及调用方法详解 - 父组件如何访问子组件方法

原文地址: https://www.cveoy.top/t/topic/qim3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录