Vue / 系统课时
组件公开能力
组件公开能力
父组件通过模板 ref 拿到子组件实例时,如果子组件使用 <script setup>,内部变量默认不会全部暴露。defineExpose 可以把父组件真正需要的状态和方法整理成一个最小公开接口,避免父组件依赖子组件的实现细节。
学习目标
- 使用
defineExpose明确子组件允许父组件访问的能力 - 为模板 ref 定义稳定的 TypeScript 公开接口
- 区分适合公开的方法、状态与应保持私有的实现细节
把模板 ref 当成受控接口
模板 ref 适合处理命令式能力,例如聚焦输入框、重置表单、滚动到指定位置或读取少量即时状态。它不应取代常规的数据流:持续业务数据仍应通过 props 传入,状态变化通常通过 emits 向上通知。
在 <script setup> 中,组件默认是封闭的。只有传给 defineExpose 的成员才会成为父组件可访问的公开表面,因此公开列表本身就是组件接口设计的一部分。
定义最小公开契约
主示例实现一个计数面板。父组件只能读取当前计数,并调用 reset 与 focusInput;输入框 DOM ref 和其他内部变量保持私有。
片段示例(counter-panel.types.ts,定义父组件依赖的接口):
export interface CounterPanelExpose {
readonly count: number
reset: () => void
focusInput: () => void
}片段示例(CounterPanel.vue,公开有限能力):
<script setup lang="ts">
import { ref } from 'vue'
import type { CounterPanelExpose } from './counter-panel.types'
const count = ref(0)
const inputEl = ref<HTMLInputElement | null>(null)
function increment() {
count.value += 1
}
function reset() {
count.value = 0
}
function focusInput() {
inputEl.value?.focus()
}
defineExpose<CounterPanelExpose>({
get count() {
return count.value
},
reset,
focusInput,
})
</script>
<template>
<div>
<input ref="inputEl" value="可被父组件命令式聚焦" />
<p>当前计数:{{ count }}</p>
<button type="button" @click="increment">+1</button>
</div>
</template>片段示例(App.vue,通过模板 ref 使用公开接口):
<script setup lang="ts">
import { ref } from 'vue'
import CounterPanel from './CounterPanel.vue'
import type { CounterPanelExpose } from './counter-panel.types'
const panelRef = ref<CounterPanelExpose | null>(null)
function resetAndReport() {
panelRef.value?.reset()
console.log('reset count =', panelRef.value?.count)
}
function focusChildInput() {
panelRef.value?.focusInput()
}
</script>
<template>
<CounterPanel ref="panelRef" />
<button type="button" @click="resetAndReport">父组件重置</button>
<button type="button" @click="focusChildInput">父组件聚焦输入框</button>
</template>预期结果:
点击子组件“+1”后,页面计数递增。
点击“父组件重置”后,计数回到 0,控制台输出:reset count = 0
点击“父组件聚焦输入框”后,焦点移动到子组件输入框。不要把内部实现全部暴露
inputEl、increment 和内部响应式状态没有必要直接交给父组件,因此不应出现在 defineExpose 中。父组件一旦开始调用这些内部成员,子组件稍微重构就可能破坏外部代码。
公开方法最好表达业务意图,例如 reset()、validate()、open(),而不是暴露 DOM 节点让父组件自己操作。公开状态也应尽量只读;如果父组件需要持续控制某个值,优先改成受控 prop 与 emit,而不是让父组件通过 ref 直接改子组件状态。
什么时候该用 defineExpose
命令式交互、第三方控件包装和表单组件通常是合适场景,因为父组件确实需要触发一个动作。普通业务状态同步则应继续保持 Vue 的声明式数据流。
判断标准很直接:如果父组件关心的是“子组件现在做一个动作”,模板 ref 加 defineExpose 通常合适;如果关心的是“这个值持续由谁拥有、如何同步”,应优先设计 props、emits 或共享状态契约。