vue3 ref获取子组件方法
时间: 2025-02-18 08:23:18 浏览: 45
### Vue 3 使用 `ref` 调用子组件方法
在 Vue 3 的组合式 API 中,父组件可以通过 `ref` 来获取子组件的实例并调用其公开的方法。为了实现这一点,在子组件中需要使用 `defineExpose` 显式暴露希望被外界访问的内容。
#### 子组件定义方法并暴露接口
子组件内部不仅能够定义数据还可以定义函数作为方法,并通过 `defineExpose` 将这些成员暴露出去以便于其他地方(比如父级)可以直接引用它们[^2]。
```javascript
<script setup lang="ts">
import { ref } from 'vue'
// 定义一个计数器变量
const count = ref(0)
// 增加计数器数值的方法
function increment() {
count.value++
}
// 向外暴露特定的数据和方法
defineExpose({
count,
increment
})
</script>
```
#### 父组件创建引用并调用子组件方法
父组件利用 `<template>` 标签内的特殊语法来设置对子组件实例的引用名称,之后就可以在这个作用域内像操作普通 JavaScript 对象一样去读取或修改已暴露出的属性以及执行相应的方法了[^1]。
```html
<template>
<!-- 创建名为 childRef 的引用 -->
<child-component ref="childRef"></child-component>
<button @click="callChildMethod">点击增加子组件中的count</button>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import ChildComponent from './path/to/ChildComponent.vue' // 导入子组件路径需替换为实际位置
// 获取子组件实例的引用
const childRef = ref(null)
// 方法用于触发按钮事件处理程序
function callChildMethod() {
if (childRef.value && typeof childRef.value.increment === 'function') {
childRef.value.increment()
}
}
</script>
```
阅读全文
相关推荐


















