options api 中父组件可通过 $refs 直接调用子组件 methods、访问 data 和 computed,无需 defineexpose;需确保子组件已挂载,且 ref 名称一致。

在 Options API 中,父组件通过 $refs 调用子组件方法是直接且明确的,不需要 defineExpose(那是 Composition API <script setup></script> 的机制)。只要子组件在 methods、data 或 computed 中定义了可访问的成员,父组件就能通过 $refs.xxx 访问并调用。
关键前提是:子组件必须已挂载,且父组件在合适的时机(如 mounted 或事件回调中)调用。
✅ 正确写法:子组件定义方法,父组件用 $refs 调用
子组件(ChildComponent.vue)
<template><div>我是子组件</div>
</template><script>
export default {
name: 'ChildComponent',
data() {
return {
internalCount: 0
}
},
methods: {
// 这个方法默认对外可见,无需额外暴露
resetCount() {
this.internalCount = 0
console.log('计数已重置')
},
sayHi(name) {
return `Hello, ${name}!`
}
}
}
</script>
父组件(ParentComponent.vue)
<template><div>
<childcomponent ref="child"></childcomponent><button>调用子组件方法</button>
</div>
</template><script>
import ChildComponent from './ChildComponent.vue'
export default {
name: 'ParentComponent',
components: { ChildComponent },
methods: {
callChildMethod() {
// ✅ 直接通过 $refs.child 访问子组件实例
const child = this.$refs.child
if (child) {
child.resetCount() // 调用方法
console.log(child.sayHi('Vue')) // 带参数调用,返回值可接收
}
}
}
}
</script>
⚠️ 注意事项
-
$refs.child拿到的是完整的子组件实例(即VueComponent实例),等同于 Vue2 中的this,所以它能访问:-
data中的数据(如child.internalCount) -
methods中的方法(如child.resetCount()) -
computed属性(如child.someComputed) -
props(只读)、$emit等所有实例属性
-
不需要
defineExpose—— 这是<script setup></script>的专属语法,在 Options API 中不生效,也不需要。$refs是异步更新的,确保在mounted后或 DOM 渲染完成后再访问(比如放在按钮点击里通常没问题;若在created中立即用,$refs.child可能为undefined)。如果子组件是异步加载(如
defineAsyncComponent),需等其加载完成再调用,否则$refs.child可能为空。
❌ 常见错误
- 在
created钩子中直接写this.$refs.child.resetCount()→ 此时子组件尚未挂载,$refs.child为undefined - 在子组件中用
<script setup></script>却误以为 Options API 写法也适用defineExpose→ 不兼容,会报错或无效 - 给
ref起名和$refs访问名不一致,例如模板写ref="myChild",代码却写this.$refs.child→ 名字必须严格匹配
这样写就是 Options API 下最标准、最稳妥的调用方式,清晰、可靠、无需额外封装。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











