在 vue 3 中,调用子组件方法有三种方法:通过 refs(使用 $refs 访问实例),通过 v-on 事件绑定(监听自定义事件并触发),以及通过 provide/inject(在父组件中注入,在子组件中获取)。

如何调用 Vue 3 子组件的方法?
在 Vue 3 中,可以通过以下方法调用子组件的方法:
1. 通过 refs:
- 在父组件中,使用
ref将子组件实例存储为变量。 - 通过
$refs访问子组件实例,并调用其方法。
<code class="js">// 父组件
<template>
<ChildComponent ref="child" />
</template>
<script>
export default {
methods: {
callChildMethod() {
this.$refs.child.someMethod();
}
}
}
</script>
// 子组件
<template>
<button @click="someMethod">Click Me</button>
</template>
<script>
export default {
methods: {
someMethod() {
console.log('Called from child component!');
}
}
}
</script></code>2. 通过 v-on 事件绑定:
立即学习“前端免费学习笔记(深入)”;
- 在父组件中,使用
v-on事件绑定监听子组件发出的自定义事件。 - 在子组件中,触发自定义事件并传递所需的参数。
<code class="js">// 父组件
<template>
<ChildComponent @custom-event="callChildMethod" />
</template>
<script>
export default {
methods: {
callChildMethod(params) {
console.log(`Child method called with params: ${params}`);
}
}
}
</script>
// 子组件
<template>
<button @click="triggerEvent">Click Me</button>
</template>
<script>
export default {
methods: {
triggerEvent() {
this.$emit('custom-event', 'My parameter');
}
}
}
</script></code>3. 通过 provide/inject:
- 在父组件中,使用
provide注入一个方法或值到其子组件。 - 在子组件中,使用
inject来获取已注入的方法或值。
<code class="js">// 父组件
<template>
<ChildComponent />
</template>
<script>
export default {
provide() {
return {
callChildMethod: this.callChildMethod
};
},
methods: {
callChildMethod() {
console.log('Called from parent component!');
}
}
}
</script>
// 子组件
<template>
<button @click="callParentMethod">Click Me</button>
</template>
<script>
export default {
inject: ['callChildMethod'],
methods: {
callParentMethod() {
this.callChildMethod();
}
}
}
</script></code>










