vue 2 中父组件可通过 $refs 调用子组件 methods 中定义的方法:需在子组件 methods 声明方法,在父组件模板用 ref="name" 绑定,在父组件 methods 中通过 this.$refs.name.method() 调用,并注意挂载时机与存在性判断。

在 Vue 2 的 Options API 中,父组件可以通过 $refs 获取子组件实例并调用其定义的方法,前提是子组件已正确注册引用且方法是公开可访问的(即定义在 methods 选项中)。
1. 在子组件中定义要暴露的方法
确保子组件在 methods 选项中声明目标方法,不需要额外修饰(Vue 2 默认所有 methods 都是响应式可调用的):
// ChildComponent.vue
export default {
methods: {
focusInput() {
const input = this.$refs.inputField;
if (input) input.focus();
},
resetForm() {
this.form = { name: '', email: '' };
}
}
}
2. 在父组件模板中为子组件添加 ref 属性
使用 ref 指令为子组件标签指定一个唯一 ref 名称(注意:不是绑定 :ref,而是静态字符串):
<template><div>
<child-component ref="childComp"></child-component><button>聚焦子组件输入框</button>
</div>
</template>
3. 在父组件 methods 中通过 $refs 调用子组件方法
在父组件的 methods 中,通过 this.$refs.refName 访问子组件实例,然后直接调用其方法:
export default {
methods: {
callChildMethod() {
// 确保子组件已挂载且 ref 存在(尤其在 v-if 或异步场景下)
if (this.$refs.childComp) {
this.$refs.childComp.focusInput();
}
}
}
}
注意:如果子组件被 v-if 控制、或尚未完成挂载(例如在 created 钩子中立即访问),this.$refs.childComp 可能为 undefined。推荐在 mounted 后调用,或加存在性判断。
4. 补充说明:ref 不适用于函数式组件或 v-for 动态列表
若子组件是函数式组件,它没有实例,$refs 将无法获取其方法;若用 v-for 渲染多个子组件,ref 会返回数组,需按索引访问(如 this.$refs.childList[0].focusInput())。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











