- 使用
ref
属性(推荐方式)- 步骤一:在父组件中给子组件添加
ref
属性- 在父组件的模板中,给子组件标签添加
ref
属性,用于获取子组件的引用。例如,有一个父组件Parent.vue
和子组件Child.vue
,在Parent.vue
中:
<template> <div> <h1>父组件</h1> <Child ref="childComponentRef"></Child> <button @click="callChildMethod">调用子组件方法</button> </div> </template> <script setup> import { ref } from 'vue'; import Child from './Child.vue'; const childComponentRef = ref(null); const callChildMethod = () => { if (childComponentRef.value) { // 假设子组件有一个名为childMethod的方法 childComponentRef.value.childMethod(); } }; </script>
- 在父组件的模板中,给子组件标签添加
- 步骤二:在子组件中暴露方法(使用
defineExpose
)- 在子组件
Child.vue
中,通过defineExpose
函数将希望被父组件调用的方法暴露出来。
<template> <div> <h2>子组件</h2> </div> </template> <script setup> const childMethod = () => { console.log('子组件的方法被调用了'); }; // 将方法暴露给父组件 defineExpose({ childMethod }); </script>
- 在子组件
- 步骤一:在父组件中给子组件添加
- 通过
$parent
访问(不推荐,耦合性强)- 这种方式是通过
$parent
属性来访问父组件。在子组件中,$parent
指向父组件实例。但是这种方式会使组件之间的耦合性变强,不符合组件化的设计理念。 - 示例:假设父组件中有一个方法
parentMethod
,子组件想要调用它- 父组件(
Parent.vue
)<template> <div> <h1>父组件</h1> <Child></Child> </div> </template> <script setup> import Child from './Child.vue'; const parentMethod = () => { console.log('父组件的方法被调用了'); }; </script>
- 子组件(
Child.vue
)<template> <div> <h2>子组件</h2> <button @click="callParentMethod">调用父组件方法</button> </div> </template> <script setup> const callParentMethod = () => { // 通过$parent访问父组件方法 if (this.$parent && typeof this.$parent.parentMethod === 'function') { this.$parent.parentMethod(); } }; </script>
- 父组件(
- 不过在Vue 3中,
$parent
的使用可能会受到一些限制,并且这种方式破坏了组件的封装性,不建议在实际开发中大量使用。通常情况下,优先考虑使用ref
来获取子组件引用并调用其方法。
- 这种方式是通过
vue3 父组件调用子组件方法
最新推荐文章于 2025-04-14 16:46:06 发布